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

1

1

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.?

Brachypterous answered 29/9, 2020 at 16:13 Comment(2)
It is quite difficult if you ask for an opinion, would be great to check what you have tried and start from that to give a better approachMajuscule
Only way to do this is via a selector. Otherwise React won't be notified about the change.Fumigator
O
3

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.

Oration answered 8/12, 2020 at 12:5 Comment(3)
Thumbs up. Recoil Nexus is a great addition to recoil!Ramiah
"You generally don't want to run into this" - do you mind explaining the "why" for that to someone new to recoil? Thank you in advance!Susannahsusanne
@Susannahsusanne In a nutshell, you want to make sure to use Recoil native hooks whenever possible: you don't want to abuse this bridge. I have even seen in some projects getRecoil and setRecoil inside components - which is a completely unnecessary abstraction.Equilibrist

© 2022 - 2024 — McMap. All rights reserved.