here I have a state which contains of client info:
const { info, setInfo, onPostInfoChanges } = useContext(ClientInfos);
Below it, is a function that post or put new infos to server:
const onSubmitHandler = async (model) => {
const emptyInputs = invalidInputs(model);
if (emptyInputs.length) {
emptyInputs.forEach((key) =>
setError((prev) => ({ ...prev, [key]: true }))
);
} else {
const response = await Save(model);
setAllClient((currentArray) => [response, ...currentArray]);
closeModal();
setError({});
}
};
I wanna execute onSubmitHandler when info state changed.
"onPostInfoChanges is a function that handle input change event"
CodePudding user response:
I think you can just use useEffect hook with info
as dependency.
It should look something like this,
useEffect(() => {
// Your code that you want to run whenever the info stat is changed
...
onSubmitHandler(model)
...
},[info])
I think this is what you want.
CodePudding user response:
You can use the useEffect
hook with info
as a dependency to execute the onSubmitHandler when the info
state is changed.
useEffect(() => {
onSubmitHandler(model)
},[info])
Now, this useEffect hook identifies the change in the info state and execute the onSubmitHandler.
Refer to this doc for more information about React useEffect hook