I have a save function in a component that makes some calls to an API and changes my local state based on the response. I then want to dispatch an action once AND ONLY ONCE these calls to setState are complete e.g.
const [myData, setMyData] = useState([{id: 0, name: "Alex"}]);
const save = async () => {
if (someCondition) {
let response = await axios.get("/someroute");
if (response.status === 200) {
setMyData([...myData, response.data])])
}
}
if (someOtherCondition) {
let response2 = await axios.get("/someotherroute");
if (response2.status === 200) {
setMyData([...myData, response2.data])])
}
}
dispatch(myAction(myData));
}
Now I know that useEffect should be the way to go about this. e.g.
useEffect(() => {
dispatch(myAction(myData));
}, [myData]);
however i'm changing myData at other places in the component, and I only want to dispatch the action once save() has been called and the setMyData calls have finished. I can't think of a condition to check for in useEffect() except maybe adding some kind of flag to myData, like an object saying "Ready to save", but it feels like there should be a simpler way.
Massively appreciate any help on this one!