Solution 1:
call RecoilNexus
at root file as App.tsx
or index.tsx
return (
<RecoilNexus />
)
then, you can call getRecoil
for get recoil state and setRecoil
for set recoil state
import {setRecoil, getRecoil, getRecoilPromise, resetRecoil} from '@components/RecoilNexus';
export const tokenState = atom({
key: "tokenState",
default: "",
});
const onSetTokenState=setRecoil(tokenState)
onSetTokenState("abc")
const tokenRecoilState=getRecoil(tokenState)
console.log(tokenRecoilState)
RecoilNexus.tsx
import {RecoilValue, RecoilState, useRecoilCallback} from 'recoil';
interface Nexus {
get?: <T>(atom: RecoilValue<T>) => T;
getPromise?: <T>(atom: RecoilValue<T>) => Promise<T>;
set?: <T>(
atom: RecoilState<T>,
valOrUpdater: T | ((currVal: T) => T),
) => void;
reset?: (atom: RecoilState<any>) => void;
}
const nexus: Nexus = {};
export default function RecoilNexus() {
nexus.get = useRecoilCallback<[atom: RecoilValue<any>], any>(
({snapshot}) =>
function <T>(atom: RecoilValue<T>) {
return snapshot.getLoadable(atom).contents;
},
[],
);
nexus.getPromise = useRecoilCallback<[atom: RecoilValue<any>], Promise<any>>(
({snapshot}) =>
function <T>(atom: RecoilValue<T>) {
return snapshot.getPromise(atom);
},
[],
);
nexus.set = useRecoilCallback(({set}) => set, []);
nexus.reset = useRecoilCallback(({reset}) => reset, []);
return null;
}
export function getRecoil<T>(atom: RecoilValue<T>): T {
return nexus.get!(atom);
}
export function getRecoilPromise<T>(atom: RecoilValue<T>): Promise<T> {
return nexus.getPromise!(atom);
}
export function setRecoil<T>(
atom: RecoilState<T>,
valOrUpdater: T | ((currVal: T) => T),
) {
nexus.set!(atom, valOrUpdater);
}
export function resetRecoil(atom: RecoilState<any>) {
nexus.reset!(atom);
}
Solution 2:
Wrap the Function component around the Class component and pass the recoil state or setter function as a prop like this
function LoginCompnentWrapper(props) {
const [token, setToken] = useRecoilState(myAtom);
return <LoginComponent {...props} token={token} setToken={setToken} />
}