I have a form component in a Material UI <Tab />
which allows users to update their address info. The information is fetched from the API via redux-thunk
and the form fields are filled with data from the server before the update has happened.
The problem is that after the user fills the fields with new data and updates their address, the form fields still show the previous state and don't update until the user reloads the page.
To fix the problem, I have implemented useEffect
to dispatch the action of fetching user data whenever the isUpdated
state is true (which will happen after the updateUserAddress
action is fulfilled). This, of course, introduced another issue which was infinite rendering.
In order to fix the infinite dispatch call, I dispatch an action to clear the update state and set it to false in the useEffect
's cleanup function. This has solved the issue and whenever the user updates their address, the UI updates and the new values populate the form fields:
// Refresh user after address update
useEffect(() => {
if (updateState) {
dispatch(getUser(userInfo.user_id));
}
// Clear update state
return () => dispatch(clearUpdateState());
}, [dispatch, updateState, userInfo]);
The only problem is that the cleanup function is called every time the user changes back and forth from the Edit Address
tab.
Although this approach has fixed my problem, I was skeptical about it and wanted to know if this is the right way of doing this.