Search code examples
reactjsreact-context

data not updating in component after adding new object to an array reactjs


i'm using context API that's why i defined object(which is array inside it) outside of functionProvider, and inside function I'm adding new object to an array which is working. when I check in console.log new item is added but in component where I'm mapping is not updated

let data = {
    todos: [...],
}

export function TodoProvider({ children }) {    
    const addNewTask = (title, setTitle) => {
        let lastId = data.todos.length
        data.todos = [...data.todos, { title, completed: false, id: lastId + 1 }]
        setTitle("")
        // WHEN I CONSOLE.LOG HERE NEW OBJECT IS ADDED
    }

    return (
        <TodoContext.Provider value={{ data, addNewTask }}>
            {children}
        </TodoContext.Provider>
    )
}

the component where I'm mapping

export default function TodoList() {
    const { data } = useContext(TodoContext)

    return (
        <ul>
            {data.todos.length ? (
                data.todos.map((item) => {
                    return <TodoItem {...item} />
                })
            ) : (
                <h2>Nothing in todolist yet</h2>
            )}
        </ul>
    )
}


Solution

  • You should set data as a state

    const [data, setData] = useState({
        todos: [...],
    })
    
    const addNewTask = (title, setTitle) => {
        let lastId = data.todos.length
        setData({ todos: [...data.todos, { title, completed: false, id: lastId + 1 }] })
        setTitle("")
    }