0

I am currently writing my context API like so:

import React, { useState, createContext, SetStateAction } from 'react'

type LoginContextProps = [boolean, React.Dispatch<SetStateAction<boolean>>]

export const LoginContext = createContext<LoginContextProps>([])

export const LoginProvider = ({
  children,
}: React.PropsWithChildren<unknown>) => {
  const [isLogin, setIsLogin] = useState(false)
  return (
    <LoginContext.Provider value={[isLogin, setIsLogin]}>
      {children}
    </LoginContext.Provider>
  )
}

I am however unsure how to satisfy typescript on the createContext portion of the code, what two objects can I pass through to make typescript type aware and not complain?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
lukeet
  • 461
  • 1
  • 4
  • 22

3 Answers3

1

You need to provide a valid default context, and it should satisfy the type LoginContextProps. For example, it may be [false, () => {}]. [] that you used is not a valid value since it's empty, but every component that happens to be outside of any LoginContext.Provider will expect that LoginContext will provide them a boolean and a boolean setter.

Nikita Ivanov
  • 767
  • 5
  • 17
  • Thank you very much works perfectly, I tried giving it the type boolean etc but it wasn't working glad the fix is so easy! – lukeet Apr 27 '21 at 11:29
0

You can simply make them optional:

type LoginContextProps = {
  isLogin?: boolean, 
  setIsLogin?: React.Dispatch<SetStateAction<boolean>>
}
Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25
-1
import React, { useState, createContext, SetStateAction } from 'react'

type LoginContextProps = [boolean, React.Dispatch<SetStateAction<boolean>>]
type LoginProviderProps = {
   children: React.ReactNode
}
export const LoginContext = createContext<LoginContextProps>([])

export const LoginProvider = ({
  children,
}: LoginProviderProps) => {
  const [isLogin, setIsLogin] = useState<boolean>(false)

  const  values: LoginContextProps = [isLogin, setIsLogin]

  return (
    <LoginContext.Provider value={values}>
      {children}
    </LoginContext.Provider>
  )
}

Nver Abgaryan
  • 621
  • 8
  • 13