Reputation: 93
I have this code
useEffect(() => {
console.log('SHOWING LAYOUT');
return () => {
if (!auth.isChangePasswordSuccess) {
console.log('SHOWING LAYOUT 2', auth.isChangePasswordSuccess);
dispatch(updateAuth('status', userStatus.LOGGED_IN));
}
}
}, [auth.isChangePasswordSuccess]);
On the first load of the screen, 'SHOWING LAYOUT' appears on my console with the auth.isChangePasswordSuccess having a value of false. But when I change the value auth.isChangePasswordSuccess to true, useEffect() is triggered displaying the 'SHOWING LAYOUT 2' in the console, but the value of auth.isChangePasswordSuccess is still false.
Any idea why the value of the redux state is not affected in the chain function call? I confirmed with the other my other useEffect() that the value is already changed to true.
Upvotes: 2
Views: 1001
Reputation: 171
I think you can not return your function, you could go in a little different way.
useEffect(() => {
console.log('SHOWING LAYOUT');
if (auth.isChangePasswordSuccess) {
console.log('SHOWING LAYOUT 2', auth.isChangePasswordSuccess);
dispatch(updateAuth('status', userStatus.LOGGED_IN));
}
}, [auth.isChangePasswordSuccess]);
let me know if this works!
I think the function returned by the useEffect
is run before every "re-run" of it, so it means that the "SHOWING LAYOUT 2" that is shown on console, is the function created at the first time the useEffect
was run, before the variable is changed.
Upvotes: 2
Reputation: 39270
The function you return from an effect is the cleanup function and would show the previous value of auth.isChangePasswordSuccess
. This because when auth.isChangePasswordSuccess
changes it will first run the cleanup which has the previous value in it's closure and then run the effect which has the current value in it's closure. Here is an example:
const { useEffect } = React;
const Component = ({ auth }) => {
useEffect(() => {
console.log(
'current value in effect function:',
auth.isChangePasswordSuccess
);
//returning cleanup function
return () => {
console.log(
'auth.isChangePasswordSuccess changed, running cleanup'
);
console.log(
'previous value (value when the cleanup was CREATED)',
auth.isChangePasswordSuccess
);
};
}, [auth.isChangePasswordSuccess]);
return String(auth.isChangePasswordSuccess);
};
const App = () => {
const [auth, setAuth] = React.useState({
isChangePasswordSuccess: true,
});
return (
<div>
<button
onClick={() =>
setAuth((auth) => ({
...auth,
isChangePasswordSuccess: !auth.isChangePasswordSuccess,
}))
}
>
toggle isChangePasswordSuccess
</button>
<Component auth={auth} />
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 5