I am creating a todo application using React hooks. The way I am doing this is by creating a context for a single todo and a context for all todos. The NewTodoContext would be parent to the new todo react components and will take up responsibilities like having an internal state, providing callback to update that state, reset that state and update AllTodosContext once user confirms todo formation.
The NewTodoProvider would look like
function NewTodoProvider({ children }){
const [todo, setTodo] = React.useState(DEFAULT_EMPTY_TODO_STATE);
const [ addTodo ] = React.useContext(AllTodosContext);
const updateTodo = React.useCallback((todoFragment) => {
// setTodo({...todo, ...todoFragment})
}, [todo]);
const confirmTodo = React.useCallback(() => { addTodo(todo) }, [todo]);
return (
<NewTodoContext.Provider value={{ todo, updateTodo, confirmTodo }}>
{ children }
</NewTodoContext.Provider>
)
}
The AllTodosProvider would look like
function AllTodosProvider({ children }){
const [todos, setTodos] = React.useState();
const addTodo = React.useCallback((todo) => {
setTodos([...todos, todo]);
},[todos]);
return (
<AllTodosContext.Provider value={{ todos, addTodo }}>
{ children }
</AllTodosContext.Provider>
)
}
and the React tree would be like
<AllTodosProvider>
<DifferentComponents />
<NewTodoButton />
<DifferentComponents />
</AllTodosProvider>
// NewTodoButton would open up into
<NewTodoProvider>
<SomeFormComponent />
</NewTodoProvider>
Now coming to the issue I am facing. As you can see, the confirmTodo is wrapped in useCallback with todo as a dependency so that it has the latest state of NewTodoProvider, but that doesn't seem to be the case. When confirmTodo is called, it seems to pick up the default state, hinting that its implementation remained unchanges inspite of state changes. What am I missing here?