'How can i write(=update) Localstorage object in Recoil Atom?
I try to get LocalStorge value for update Recoil atom object value below code.
const LoginState = atom({
key: 'login',
default : null
});
const Home: NextPage = () => {
const [login, setLogin] = useRecoilState(LoginState)
useEffect(()=>{
let localData = localStorage.getItem("token")
if(login === null || undefined){
if(localData !== null || undefined){
setLogin(localData)
}else{
setLogin(null)
}
}
}, [login])
but it has error like this.
Argument of type 'string | null' is not assignable to parameter of type '((currVal: null) => null) | null'.
Type 'string' is not assignable to type '((currVal: null) => null) | null'**.ts(2345)**
<br>
i reckon this problem is came from type. As far as I know type of localStorage object is string or null How can i solve it?
Solution 1:[1]
I found solution when i write question.
atom object need to type.
First, you define type that uses in atom
type loginState = {
localValue : string | null
}
Second, add type that was defined to atom object like this
const LoginState = atom<loginState>({
key: 'login',
default : {
localValue : null
}
});
Last, you can fix according to your type
useEffect(()=>{
let localData = localStorage.getItem("token")
if(login === null || undefined){
if(localData !== null || undefined){
setLogin({localValue : localData})
}else{
setLogin({localValue : null})
}
}
}, [login])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Boris Park |
