I included an empty array because this should only run once, however I'm getting the linting warning because I'm not including ajaxCallsInProgress
as a dependency. The reason I don't is that it creates an infinite loop if I do. Is there a better way to handle this scenario that will eliminate the linting warning? This is pretty straight-forward and a valid scenario as far as I can tell.
useEffect(() => {
const fetch = async () => {
// update state to show pending
setAjaxCallsInProgress(ajaxCallsInProgress + 1)
try {
const humans = await getHumans()
setHumans(humans)
} catch (error) {
setError(error)
} finally {
setAjaxCallsInProgress(ajaxCallsInProgress - 1)
}
}
fetch()
}, [])
In-/decrementing the state doesn't require you to know the current state because setState
has a callback version that receives the current state as an argument and returns the next state:
const [ajaxCallsInProgress, setAjaxCallsInProgress] = useState(0);
useEffect(() => {
const fetch = async () => {
// update state to show pending
setAjaxCallsInProgress(current => current + 1)
try {
const humans = await getHumans()
setHumans(humans)
} catch (error) {
setError(error)
} finally {
setAjaxCallsInProgress(current => current - 1)
}
}
fetch()
}, [])
This will remove the dependency on ajaxCallsInProgress
and is also a best practice for updating state based on the current state:
How do I update state with values that depend on the current state?
Pass a function instead of an object to
setState
to ensure the call always uses the most updated version of state (see below).
You should generally use it when accessing the current state to update the state.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.