Issue
I'm trying to use useEffect to clean up states when the component unmounts, but it's interfering when I try to set the states. My code is based on clicking in a client and setting this client id to send in a api request:
const setClient = () => {
setClientIdForRegister(id)
setClientNameForRegister(nome)
}
return (
<ClientSearchResultInfos onClick={setClient}>
<div className="client_and_email">
<h2>{nome}</h2>
<span>{email}</span>
</div>
<CaretRight size={30} />
</ClientSearchResultInfos>
)
The request:
const handleRegisterReceipt = async (data: FormDataProps) => {
try {
const dataToSend = {
cliente: {
id: clientIdForRegister,
},
dataPagamento: data.dataPagamento,
valor: data.valor,
}
const response = await api.post('/pagamentos', dataToSend)
}
When the user clicks in the client it's supposed to set the value of the input of the form with the client's name:
useEffect(() => {
const getClientName = async () => {
if (clientNameForRegister) {
setValue('cliente', clientNameForRegister)
}
}
getClientName()
}, [setValue, clientNameForRegister])
I triend using return inside the parent's component useEffect, so when I leave the page and come back, the id and name are null again
// parent component:
const cleanUp = () => {
setClientNameForRegister(null)
setClientIdForRegister(null)
}
useEffect(() => {
return cleanUp
})
But this causes the sent clientIdForRegister to always be null, because the component always re-renders and runs cleanUp.
I also tried like this:
// parent component:
const isMountedRef = useRef<boolean>(true)
useEffect(() => {
return () => {
isMountedRef.current = false
if (isMountedRef.current) {
setClientNameForRegister(null)
setClientIdForRegister(null)
}
}
})
This way doesn't set the clientIdForRegister null, but it doesn't clear the name and id when the component unmounts.
Is there a way I can clear the states every time the user leaves the page and still send the clientIdForRegister?
Solution
The first method you tried is the best practice, you just missed ", []" at the end, which resulted going into return on every re-render.
this way return only executes when component unmounts, hence like this will work:
const cleanUp = () => {
setClientNameForRegister(null)
setClientIdForRegister(null)
}
useEffect(() => {
return cleanUp()
}, [])
Answered By - Mathe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.