I have a simple form for search user by email in JSON file:
I want next feature: when user click on button, oldest requests should be cancelled. In this project I set timeout 5 sec on getting data. That mean, if I write first email, than click button and write second email and click less then 5 sec, I should get only data about second user.
To store the found data I have react context. How you can see, I try to use AbortController, but it don't work. Firstly I get data about first user and after 1 sec I get data about second user.
const { createContext, useState, useContext} = require("react")
const FindedDataContext = createContext()
export const useFindedData = () => useContext(FindedDataContext)
export const FindedDataProvider = ({children}) =>{
const [findedData, setFindedData] = useState()
const abortController = new AbortController()
const cancelLastFetch = async () => abortController.abort()
const findData = async ({email, number}) =>{
const {signal} = abortController
console.log(signal);
cancelLastFetch()
return await fetch('http://localhost:5000/api?' + new URLSearchParams({
email,
number
}, {signal})
)
.then(res => res.json())
.then(data => setFindedData(data))
.catch(err => console.log(err))
}
return(
<FindedDataContext.Provider value={{findedData, findData, cancelLastFetch}}>
{children}
</FindedDataContext.Provider>
)
}
Code on Search button:
const submitForm = async () =>{
setValidationError({...validationError, email: null})
await findData(formData)
}
