I am new to recoil, and I am using all class components. Here is my recoil state
export const tokenState = atom({
key: "tokenState",
default: "",
});
How to use recoil in class component and set the token?
I have used RecoilRoot
in app as
<RecoilRoot>
<Header />
<Main />
</RecoilRoot>
In login.js
, I want to set the token in recoil, but login.js
is a class component.
const res = await APIS.login(apiRoute,requestObject);
In res.data.token
I am getting the jwt token.
Thank you in advance!
Recoil.JS is meant to be used with react hooks, I don't think they provide any other functions other than hooks. If you can't change Login.js to a functional component try using a wrapping functional component that passes the token as prop to the login.js component.
I'd suggest useRecoilState(myAtom)
.
function LoginWrapper(props) {
const [token, setToken] = useRecoilState(myAtom);
useEffect(() => {
async function get() {
const { data: { token: jwt } } = await APIS.login(apiRoute,requestObject);
setToken(jwt);
}
get();
}, []);
return <LoginComponent {...props} jwt={token} />
}