Update #1
Since posting this (7 hours ago), I tried to do this myself, and realised I completely invented this feature, and callback isn't actually a function of useState
I did some research and came across this very useful function:
const useStateCallback = (initialState) => {
const [state, setState] = useState(initialState);
const cbRef = useRef(null); // init mutable ref container for callbacks
const setStateCallback = useCallback((s, cb) => {
cbRef.current = cb; // store current, passed callback in ref
setState(s);
}, []); // keep object reference stable, exactly like `useState`
useEffect(() => {
// cb.current is `null` on initial render,
// so we only invoke callback on state *updates*
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null; // reset callback after execution
}
}, [state]);
return [state, setStateCallback];
};
Original
I don't know what getData
is, but I'll assume it's state, and you have something like this:
const [data, getData] = useStateCallback(); // previously useState
If that's the case, when you call your getData
, you can do a callback as the 2nd argument. That callback happens when your state updates successfully:
...
getData(JSON.stringify(result.data.result), () => console.log(data.length));
...
If that's now how you're doing it, then I'd suggest you change whatever you're doing to be in state, and also rename getData
to setData
Explanation
When you're calling your getData
, you're telling react that you want to update your data? Great! The thing to note is, react doesn't do this update immediately. Instead, it updates it (and other state) in the future, all at the same time.
With that in mind, you pass the callback function as the 2nd argument to tell react what you want to happen once this specific state has been updated
As for getData
to setData
? That's because the function doesn't return (get
) anything, but does set
something. Makes your code clearer