The example below shows how my use of useEffect() causes multiple Ajax requests. On the initial rendering of the component, this request is made twice. If the tag is changed, this request is made twice.
I can use some kind of internal state variables to track whether I have already fetched. Or I can create a kind of stack where I push on potential requests of a certain type, then before returning pop the stack and run the final request. But all of these seem like a hack.
(If it helps, the application is quite a bit larger, and I am using redux. Is a broader solution something like redux-saga's cancellation?)
const Thing => () => {
const [tagId, setTagId] = useState(null)
const [query, setQuery] = useState('')
useEffect(() => {
doSomeAjaxAndUpdateResults()
setQuery('')
}, [tagId])
useEffect(() => {
doSomeAjaxAndUpdateResults()
}, [query])
// ... bunch of extra effects with similar dependencies.
}
You can just combine both internal state variables into one useEffect hook and then if one change you can do doSomeAjaxAndUpdateResults
const Thing = (prop) => {
const [tagId, setTagId] = useState(null)
const [query, setQuery] = useState('')
useEffect(() => {
doSomeAjaxAndUpdateResults()
setQuery('')
}, [tagId, query])
return ...;
}
Here's the live example that also relies on props being passed over: https://stackblitz.com/edit/react-wzmxmj
First render is with initial value, second render is with props being passed over and then subsequent props change will trigger one call each.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With