FundBoardCo / Hamilton

0 stars 0 forks source link

Fix Caching Issue in Profile #152

Open JoshFundBoard opened 3 years ago

JoshFundBoard commented 3 years ago

In Profile.js, the attempt to be clever with the initialInputState object actually causes a bug where the inputs do not update their values if the profile object from Redux updates.

This can be seen by logging in as one user, logging out, then logging in as a new user. The inputs will still show the first user's values instead of the current values of the profile object.

The obvious way to fix this would be to break out a single useState function for each input.

JoshFundBoard commented 3 years ago

Fix Caching Issues in Profile

JoshFundBoard commented 3 years ago

I had some late night thoughts on this.

The core issue is state is maintained between renders, which is good, otherwise state would be useless.

But that means the initial state is only set on the first render, which is why when the profile values change after logging in as a new user they don't affect the current state.

I think if the profile inputs were broken out into their own component, and the profile was passed in as a prop, that would solve this. It would also take care of part of the work for #46 and #90.

An alternate solution would be to do

useEffect(() => {
  setInputState({ ...initialInputState });
}, [profile]);

That feels a bit hacky to me, but should work.

The react blog actually talks about this exact issue, and has some solutions:

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

We do have the potential issue with the solutions above that if a user is editing their profile and the profile in Redux updates, it would reset to the Redux values and erase their work, which isn't ideal, but in this specific case I think it's OK because that should only happen on a save or if you switch users, in which case we want to replace any unsaved data with whatever Redux has.