I use RXJS to help to set RecoilJS value outside of the component.
At the start, I created 4 parts as
- Main component
- RecoilJS component
- Atom file
- set RecoilJS outside value of the component file
1).Main
import React from 'react';
import {
RecoilRoot
} from 'recoil';
function App() {
return (
<RecoilRoot>
<MainScreens />
<RecoilJSComponent/>
</RecoilRoot>
);
}
2).RecoilJS component
import React from 'react';
import {
useRecoilCallback
} from 'recoil';
import { Subject } from 'rxjs';
export const setRecoil = new Subject();
const getRecoil = new Subject();
const returnRecoil = new Subject();
export const promiseGetRecoil = (recoilObj) => {
return new Promise(async (resolve, reject) => {
getRecoil.next(recoilObj)
returnRecoil.subscribe({
next: (value) => {
if (recoilObj === value.recoilObj) {
resolve(value.value)
}
}
});
})
}
export default function RecoilJSComponent() {
const setStore = useRecoilCallback(({ set }) => (n) => {
set(n.recoilObj, () => (n.value));
}, [])
const getStore = useRecoilCallback(({ snapshot }) => async (recoilObj) => {
const valueRecoilObj = await snapshot.getPromise(recoilObj);
returnRecoil.next({ recoilObj: recoilObj, value: valueRecoilObj })
}, [])
setRecoil.subscribe({
next: (value) => {
setStore(value)
}
});
getRecoil.subscribe({
next: (recoilObj) => {
getStore(recoilObj)
}
});
return null;
}
3).Atom file
export const textState = atom({
key: 'textState'
default: ''
});
4).set RecoilJS outside the value of the component file
import API from './Api';
import { setRecoil } from './RecoilJSComponent'
import { textState } from './textState'
export const setValueReCoil = () => {
API()
.then(result => {
setRecoil({ recoilObj: textState, value: result })
})
.catch(ex => {
})
};
The main idol is in 2 and 4
In number 2,
I create to use RXJS for setting value via the component and I export RXJS to set a value on RecoilJS outside of the component
I hope my idol can help you to resolve your problem