When modal.error
sets to true
, then my effect should be run:
useEffect(() => {
if (modal.error) {
setModal({...modal, prompt: false})
}
}, [modal]);
modal - is an object:
const [modal, setModal] = useState<SomeInteface>({
success: false,
error: false,
prompt: false
})
However i want in useEffect
deps only modal.error
, but when i do so, linter warns me about exhaustive/deps annoying rule, why should i put my entire object in to a deps array, instead of just one of its properties. It's obviously going for infinite loops, because object modal
is always going to change.
I still don't get, why did React team went away from lifecycle's paradigm which was so convenient instead of this 3 in one thing, which is more confusing with these exhaustive/deps rules, i've read a lot of articles about useEffect
, but still, i think lifecycles is much better.
UPDATE 1
const removePartner = (): void => {
setModal({
...modal,
prompt: false
});
deleteRequest(undefined, modal.id).then((resp: any) => {
if (resp) {
setModal({ ...modal, success: true });
} else {
setModal({ ...modal, error: true });
}
});
};
UPDATE 2
TSX part:
<Swal
show={modal.prompt}
icon={Icons.warning}
title="Warning!"
text="Are you sure?"
cancelButton={true}
onModalClose={() => setModal({ ...modal, prompt: false })}
onAccept={removePartner}
/>
<Swal
show={modal.error}
icon={Icons.error}
title="Error"
text={fetchError!}
onModalClose={() => setModal({ ...modal, error: false })}
/>
<Swal
show={modal.success}
icon={Icons.success}
title="Success!"
text="You have removed a user!"
onModalClose={() => {
setModal({ ...modal, success: false });
doFetch().then();
}}
/>
I think you don't need an useEffect. You just need to bind your state to the modal.
<Modal open={modal.error} />
You just need a condition to set the state of modal.error
I changed my mind about using objects in useState
hooks, they are meant for a primitive values, that makes sense, otherwise i recommended others to use useReducer
for complex objects. Then you won't have issues with useEffect
deps loops cause of the whole object changes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.