facebookexperimental / Recoil

Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
https://recoiljs.org/
MIT License
19.6k stars 1.19k forks source link

Option to push events into all atoms / or alternative #7

Closed RichardLindhout closed 4 years ago

RichardLindhout commented 4 years ago

I'm rewriting my app from redux to recoil, it's going great, but I did have a global 'RESET' action for example when I logout. I want some reducers to reset themselves. I think I can fix this with more explicit approach of using useResetRecoilState() in my logout button but I was wondering if you did have an alternative for that use-case.

import { atom } from 'recoil'

export const answeredFlows = atom({
  key: 'answeredFlows',
  default: [],
  globalEvents: (event: { type: string }) => {
    if (event.type === 'LOGOUT') {
      return []
    }
  },
})

I guess you don't want to recreate Redux but sometimes it would be cool to pass an event to all atoms.

davidmccabe commented 4 years ago

Thanks for your interest Richard!

As you mentioned, you can delete the value of an atom using useResetRecoilState.

If you want a reducer-style interface to atoms, you can create a hook that exposes such an interface and export that from the module instead of the atom itself.

RichardLindhout commented 4 years ago

I get what you mean. Thank you.

Spartano commented 4 years ago

I get what you mean. Thank you.

Can you share an example of you're solution.

Thank you

RichardLindhout commented 4 years ago

You could write a custom hook with exposes all useResetRecoilState and the reset function of those in one function but you would need to import them if you need to reset them

Spartano commented 4 years ago

You could write a custom hook with exposes all useResetRecoilState and the reset function of those in one function but you would need to import them if you need to reset them

What do you think about calling this method outside of a react component, like an event dispatcher as you said, and then you're custom hook will reset the store.

RichardLindhout commented 4 years ago

Yeah I did have the same use case so I did create https://github.com/web-ridge/react-ridge-state since I don't have the use-case for recoil yet and needed my state globally too