I can't use useContext Hook with TypeScript

Viewed 716

I am trying to make to-do app using TypeScript and Context API, I can't use context of to-dos with useContext Hook.

Creating Context, Here I created an interface of array to-dos and created its context.

const todos = [
    { todo: 'Make Break Fast', id: 1, completed: true },
    { todo: 'React Book', id: 2, completed: false },
    { todo: 'Start Coding', id: 3, completed: false },
]


interface ITodos {
    todo: string
    id: number
    completed: boolean
}

export const TodoContext = createContext<ITodos[]>(todos);

Global Provider, Here I Created Context Provider and passed its childrens (JSX.Elements) as Props.

interface IChildrenProp {
    children: React.ReactNode
}

const ContextProvider = ({ children }: IChildrenProp): JSX.Element => {

    return <TodoContext.Provider value={todos}>
        {children}
    </TodoContext.Provider>
}

export default ContextProvider;

Using Context, Here I am expecting my list of to-dos using useCotext Hook from TodoContext.

import React, { useContext } from 'react'
import TodoContext from './store/context'




const Todo: React.FC = (): JSX.Element => {

    const todos = useContext(TodoContext)

    return (
        <>
            <h1>My Todo List</h1>
            <input id='todo' placeholder='e.g. Read Book' />

        </>
    )
}

export default Todo

Error, But getting following error.

TypeScript error in /typescript/todo-app/src/Todo.tsx(9,30):
Argument of type '({ children }: IChildrenProp) => JSX.Element' is not assignable to parameter of type 'Context<unknown>'.
  Type '({ children }: IChildrenProp) => Element' is missing the following properties from type 'Context<unknown>': Provider, Consumer  TS2345

     7 | const Todo: React.FC = (): JSX.Element => {
     8 | 
  >  9 |     const todos = useContext(TodoContext)
       |                              ^
    10 | 
    11 | 
    12 |     return (
0 Answers
Related