4

I have the start of s simple todo app in with React and typescript

I am creating a context but getting an error in the value of the content provider

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

for the value I get the error

Type '{ todoList: string[]; }' is not assignable to type 'null'.

What does error mean and how can i fix this typescript error

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

interface AuxProps {
    children: ReactChild | ReactChildren;
  }

const TodoContext = createContext(null)

const intialTodo = ['Learn Context']

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

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

    const contextValue = {
        todoList
    }

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

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

export default TodoProvider

2 Answers 2

8

Because you are sending just null. but context needs null with type here like that

const TodoContext = createContext(null as any)
render{
 const photosObject = this.context as any
}
Sign up to request clarification or add additional context in comments.

Comments

4

Why are you assigning null to string array?

const TodoContext = createContext([])

does it work for your case?

2 Comments

I need to assign something so I was trying null, with the empty array I get Type '{ todoList: string[]; }' is missing the following properties from type 'never[]': length, pop, push, concat, and 29 more.
my apologies, I never worked with react context and took a few minutes to learn and prepared this forked sandbox codesandbox.io/s/react-context-typescript-forked-sn2hmi? please let me know if it doesn't help, then we can try it again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.