'React Typescript context, how to pass an object
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 1:[1]
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: () => {}
}
Solution 2:[2]
@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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dave |
| Solution 2 | Linda Paiste |
