Recoil - how to update an atom with socket.io correctly

2.3k views Asked by At

I have to update an atom outside of an React Component (where I can't use hooks). What is the correct way to do this in order to get the updated value in my subscribing React Components with hooks like useRecoilState etc.?

1

There are 1 answers

3
Luis Antonio Canettoli Ordoñez On

You generally don't want to run into this: I'd suggest to double check your approach first.

However, if you eventually still really need to update atoms outside of React Components you might give a try to Recoil Nexus.

In the same file where you have your RecoilRoot you'll have something like:

import React from 'react';
import { RecoilRoot } from "recoil"
import RecoilNexus from 'recoil-nexus'

export default function App() {
  return (
    <RecoilRoot>
      <RecoilNexus/>
      
      {/* ... */}
      
    </RecoilRoot>
  );
};


export default App;

Then where you need to read/update the values:

import yourAtom from './yourAtom'
import { getRecoil, setRecoil } from 'recoil-nexus'

Eventually you can get and set the values like this:


const loading = await getRecoil(loadingState)

setRecoil(loadingState, !loading)

That's it!


Check this CodeSandbox for a live example.