Home > Back-end >  React Typescript context, how to pass an object
React Typescript context, how to pass an object

Time:02-21

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

CodePudding user response:

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

CodePudding user response:

The issue is that you provided the 'type' of the getNumberTodo (function that returns void) for the value of the defaultContext object. You must provide an actual function:

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

CodePudding user response:

@youdateme is correct in explaining the error, but it seems like you don't want that void at all.

The type declaration for the context says that getNumberTodo is a function which returns void. However in your implementation const getNumberTodo = () => todoList.length you are returning a number.

I suspect that you are actually intending for getNumberTodo to return number, not void.

You can change the type of your context:

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

And change the initial value to return a number:

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