0

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.

enter image description here

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.

Nima
  • 996
  • 2
  • 9
  • 37
  • 1
    why not calling `dispatch(clearUpdateState())` inside the `if (updateState) {` statement ? – Olivier Boissé Jun 04 '22 at 18:51
  • @OlivierBoissé Thanks a lot for the answer. Your solution works as well and I'm gonna go with it. I really thought I had tried that before! – Nima Jun 05 '22 at 04:11

1 Answers1

0

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.

You can do an optimistic update when the update address action is dispatched and simply write the input data into the state - assuming that the update will probably work. This should fill the inputs with the data the user just entered, so for them nothing will change. The update request itself should return the updated data set, so you can save that in redux. Or if it doesn't, fire a get request right after the update.

timotgl
  • 2,865
  • 1
  • 9
  • 19