It's just a simple createContext and useContext code. I struggled a lot until I realised that an if statement is necessary in the useTodoContext
function. When I comment out the if statement line, then I get an error.
Can you tell me doesn't work the code without the if statement? It doesn't make sense...
Without the if statement, this is the error what I get:
Compiled with problems:X
ERROR in src/components/TaskList.tsx:12:11
TS2339: Property 'words' does not exist on type 'Context | null'.
10 |
11 | export default function TaskList({ tasks, setTasks }: props) {
> 12 | const { words } = useTodoContext();
| ^^^^^
13 |
14 | const allowDrop = (e: React.FormEvent) => {
15 | e.preventDefault();
import React, { createContext, useContext, useState } from 'react';
type Context = {
words: string[];
setWords: React.Dispatch<React.SetStateAction<string[]>>;
};
const TodoContext = createContext<Context | null>(null);
const TodoProvider = ({ children }: { children: React.ReactNode }) => {
const [words, setWords] = useState<string[]>([]);
return <TodoContext.Provider value={{ words, setWords }}>{children}</TodoContext.Provider>;
};
const useTodoContext = () => {
const context = useContext(TodoContext);
if (!context) throw new Error('Provider not inside'); // without this code line doesn't work
return context;
};
export { useTodoContext, TodoProvider };