jamiebuilds / unstated-next

200 bytes to never think about React state management libraries ever again

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] What are some recommended patterns of clearing multiple containers at once?

andrefox333 opened this issue · comments

If I have multiple containers and I need to reset the state to initialState of each one upon let say when a user logs out. What is the best way of doing this? Not having each container's Provider on the App component makes this a bit challenging... Loving the library so far - just running into these little quirks. Open to suggestions and maybe other ways of tackling this problem. Thanks!

great question i'm running into the same issue

Great question. In my experience, this is where "events" come into play -- where one component can listen for dispatched events from another component. IMO this is where this library falls down -- it ties function execution to state manipulation too closely.

Redux-like solutions really shine here.

Event dispatching/listening is incredibly powerful. In your case, maybe and Auth component dispatches "auth/logout" event, and other components listen for "auth/logout" and do whatever they need to do, eg initialState. (This ability is why I use rematch on top of redux.)

In the situation where you need to clear multiple containers when a user logs out you just need to make sure that all the <StateContainer.Provider>s you want to clear are unmounted when a user logs out.

See an example based off react router auth.

Click protected, log in, click buttons to update state, log out, then repeat to see the state being reset to the initial state. Hope that helps 👍