The Situation
I am using Recoil to manage state in a React application. I am using Atom Effects to back up recoil values with an API.
When my Atom detects something wrong with the authentication token I would like it to somehow convey that issue to the rest of the application so that the application can update state.
The Details
I have several Atoms:
- An atom which stores an authentication token, for use when communicating with the storage API.
- Atoms for various pieces of the application which I would like to save on that storage API.
In order to perform the API synchronization I have an apiStorageEffect
Atom Effect. The effect uses a recoil-stored authentication token using getPromise
and forwards changes using an onSet
handler. That handler uses the token when calling the save method. The save method can detect when authentication has failed.
When authentication fails I need to trigger a log out event (setting the token to null, and resetting a series of atoms to their defaults).
Here is a minimal version of the storage effect:
const apiStorageEffect = (key) => async ({
onSet,
getPromise,
}) => {
const authToken = await getPromise(authTokenAtom)
if (!authToken) { return }
onSet(async (newValue) => {
const result = await saveToApiStorage(key, newValue, authToken)
if (result.failed) {
// INSERT CODE TO TRIGGER LOGOUT HERE
}
})
}
The Question
I can think of a few possible paths for triggering logout from within an effect, but all of them involve somehow sending information outside of the affected atom to the main application.
- Is it possible to modify atoms OTHER than the atom / node in question from within an atom effect?
- Is it possible for an atom effect to emit an event that can be immediately handled elsewhere in the React application?
- Is it possible for an atom effect to invoke a method that can modify recoil state more broadly?