I want to trigger An API to do some actions when the value in the react state be empty, Is there a way in react state hook to achieve that?
CodePudding user response:
If you are using a functional component you can use the "useEffect" hook with a proper dependency. Class base components you might choose (if I understand your situation properly) something like the "componentWillUnmount()" method.
CodePudding user response:
You could have a useEffect
hook with the state as a dependency, in-which you can check if the state is empty and act accordingly.
Example:
const [state, setState] = useState([]);
useEffect(() => {
if (state.length !== 0) {
return;
}
// Can make your API call here (preferably call a function that does it)
// and then set the state.
setState(...);
}, [state]);
useEffect
is a hook that accepts a callback as the first argument, and a dependency array as the second.
The callback will execute upon re-render whenever any of the dependencies in the array change.
- Note: this is relevant only for functional components, for class-based component we have the
componentDidUpdate
lifecycle hook.