Home > Software design >  Get error when using createContext with typescript
Get error when using createContext with typescript

Time:05-07

I am trying to make a context with hooks in react with typescript like this:

// StateGlobalContext.ts
import React, { Dispatch, ReactNode, SetStateAction } from "react";

export interface StateGlobalContextType {
  loading: boolean
  setLoading: Dispatch<SetStateAction<boolean>>
}

export const StateGlobalContext = React.createContext<StateGlobalContextType>({} as StateGlobalContextType);

export default function StateGlobalProvider({ children: ReactNode }): React.FC<ReactNode> {
  const [loading, setLoading] = React.useState<boolean>(false);

  return (
    <StateGlobalContext.Provider value={{ loading, setLoading }}>
      {props.children}
    </StateGlobalContext.Provider>
  )
}

But for some reason i don't know why, return get problem like this

Type '{}' is missing the following properties from type 'ReactElement<any, any>': type, props, key

and i cannot declare StateGlobalContext.Provider, the error message like this

Cannot find namespace 'StateGlobalContext'

CodePudding user response:

This is an error to do with how you're handling your props input.

When destructuring in Typescript doing { children: ReactNode } destructures the children attribute from props, assigning it to a variable called ReactNode. Then, rather than calling ReactNode (which would still be an error because you've imported it too), you're using props.children, which is not defined.

Instead use the syntax: { children }: { children: ReactNode }, although this is easier if you use an interface.

import React, { Dispatch, ReactNode, SetStateAction, createContext } from "react"

export interface StateGlobalContextType {
    loading: boolean
    setLoading: Dispatch<SetStateAction<boolean>>
}

export const StateGlobalContext = createContext<StateGlobalContextType>({} as StateGlobalContextType)

interface StateGlobalProviderProps {
    children: ReactNode
}
const StateGlobalProvider: React.FC<StateGlobalProviderProps> = ({ children }: StateGlobalProviderProps) => {
    const [loading, setLoading] = React.useState<boolean>(false)

    return <StateGlobalContext.Provider value={{ loading, setLoading }}>{children}</StateGlobalContext.Provider>
}

export default StateGlobalProvider

Also, rather than declaring the return type of function as React.FC<ReactNode>, declare the component itself as type React.FC<StateGlobalProviderProps>

  • Related