reactjstypescriptnext.jsuse-context

I can't use useContext with Typescript with my react application


I am new to typescript and trying to build a Todo app with the use of 'useContext' hook using typescript-react.

I am not able to pass TodoContextProviderProps as a prop below, to my Provider function.

import React, { FC, createContext } from "react";
import { ITodo, TodoContextInterface } from "../utils/interfaces";

const TodoContext = createContext<TodoContextInterface | null>(null)

type TodoContextProviderProps = {
    children: React.ReactNode;
}

export const TodoContextProvider: FC<TodoContextProviderProps> = ({children}) => {

    const todos: ITodo[] =[]

    const saveTodo: (todo: ITodo) => {
        todos.push(todo)
    }
    const removeTodo: (id: number) => {
        //
    }

    const value = {
        todos, saveTodo, removeTodo
    }
    return <TodoContext.Provider value={value}>{children}</TodoContext.Provider>
} 

export default TodoContext

I am getting an error saying:

Type '({ children }: TodoContextProviderProps) => void' is not assignable to type 'FC<TodoContextProviderProps>'.
  Type 'void' is not assignable to type 'ReactElement<any, any> | null'.

Here are my Interfaces:

export interface ITodo {
    id: number;
    task: string;
    status: boolean;
}

export interface TodoContextInterface {
    todos: ITodo[];
    saveTodo: (todo: ITodo) => void;
    removeTodo: (id: number) => void;
}

Solution

  • You have syntax error...

     const saveTodo = (todo: ITodo) => {
            todos.push(todo)
     }
     const removeTodo = (id: number) => {
            //
     }
    

    Change :(todo: ITodo) to = (todo: ITodo). And = (id: number)

    It has to be equal sign "="

    This is why it makes this error