Search code examples
reactjsids

How not to reset ID's on reload in React?


In my React ToDo list, the todos keep having the same ID's after reloading the App.

So, if I start setting todos, they will have the id's correctly numbered: 0, 1, 2, 3, 4,...

todos: [{id: 0, text: "Create PWA", date: 1601244000000, completed: false},…]
0: {id: 0, text: "Create PWA", date: 1601244000000, completed: false}
1: {id: 1, text: "Use Hooks for Gorilla sound once", date: 1601416800000, completed: false}
...

However, If I reload, the ID's will reset:

todos: [{id: 0, text: "Create PWA", date: 1601244000000, completed: false},…]
0: {id: 0, text: "Create PWA", date: 1601244000000, completed: false}
1: {id: 1, text: "Use Hooks for Gorilla sound once", date: 1601416800000, completed: false}
2: {id: 0, text: "dsadasd", date: 1600812000000, completed: false}
...

Any ideas how to solve? CodeSandbox Link


Solution

  • based on a quick glance, your problem seems to be from the way you set the id like from the following:

    let nextTodoId = 0;
    
    export const addTodo = (todo) => ({
        type: 'ADD_TODO',
        id: nextTodoId++,
        todo
    });
    

    it's fine on first load because it will be zero and then each item added it will be incremented, but on reload it will be 0 again.

    the way to fix this will be to first check if state is present in local storage and then get the id of the last item in the list and then use that as the base id - if there is no last id, just make it 0 again

    so something like the following should work

    function getBaseId() {
        const serialzedState = localStorage.getItem("state");
        if (serialzedState === null) return 0;
        const parsedState = JSON.parse(serialzedState);
        const todos = parsedState.todos
        return todos[todos.length - 1].id;
    }
    
    let nextTodoId = getBaseId();