0

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?

Boris Park
  • 105
  • 1
  • 10

1 Answers1

0

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])
Boris Park
  • 105
  • 1
  • 10