React Typescript context, how to pass an object

Issue

I have a stackblitz here

I’m trying to create a simple todo app in React with Typescript using context

I have a context and I’m trying to pass an object in this context to use in other components

import React from 'react'
import { createContext, useContext, useState, ReactChildren, ReactChild } from "react";

interface AuxProps {
    children: ReactChild | ReactChildren;
  }

  const defaultContext = {
    todoList: ['todo', 'another todo'],
    getNumberTodo: () => void
  }

const TodoContext = createContext<{ todoList: string[], getNumberTodo: () => void }>(defaultContext)

const TodoProvider = ({children}:AuxProps) => {

    const [todoList, setTodoList] = useState<string[]>(defaultContext.todoList)

    const getNumberTodo = () => todoList.length

    const contextValue = {
        todoList,
        getNumberTodo
    }

    return(
        <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider>
    )
}

export const useTodoContext = () => useContext(TodoContext)

export default TodoProvider 

I’m trying to create a defaultContext to pass to the createContext but I get an error simple saying

Expression expected.(1109)

Is is possible to pass an object with createContext

Solution

void is an operator. It evaluates its operand on the right and returns undefined.

getNumberTodo: () => void

That’s why it’s expecting an expression.

If it’s not implemented yet, either implement the function or throw an error that says its not implemented.

Temporary solution: add a 0:

getNumberTodo: () => void 0

Answered By – youdateme

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.