MUHAMMAD Siyab
MUHAMMAD Siyab

Reputation: 446

Firebase data duplicate issue

I'm working on a React TODO app with backend firebase. The issue i'm stuck in is that the data sent from the firebase RTD is appending twice when after updating or deleting a node from the firebase RTD.

State:

// Initialize state
this.state = {
    todos: []
}

This is my getTodos function which is responsible for reading data, called inside componentDidMount:

getTodos () {
    firebase.database().ref('todos').on('value', (todo) => {
        const todos = todo.val();
        // Iterate through keys
        Object.keys(todos).map(todoItem => {                
            let todo = todos[todoItem];
            // Update the todos array
            this.setState({
                todos: [...this.state.todos, todo]
            })
        })
    })
}

Rendering section:

<tbody>
{
  this.state.todos.map((todo, index) => {
     return (
        <tr key={index}>
           <td>{index + 1}</td>
           <td>{todo.title}</td>
           <td>{todo.date}</td>
           <td align="center">
           <button className="btn btn-success btn-sm" data-toggle="modal" data-target="#editModal" onClick={this.assignID.bind(this)}>
                   <i className="fa fa-pencil"></i>
               </button> &nbsp;
               <button className="btn btn-danger btn-sm" onClick={this.removeTodo.bind(this)}>
                   <i className="fa fa-trash"></i>
               </button>
                </td>
         </tr>
          )
        })
      }
    </tbody>
}

The result (Before deleting a TODO): enter image description here

After deleting a TODO: enter image description here

I tried resetting todos state length to zero and then calling getTodos, but that didn't solve the issue. Any idea?

Upvotes: 0

Views: 1077

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

You're not clearing the existing contents of the todos in the state. Also: you're updating the state at every iteration of the loop, which is inefficient.

firebase.database().ref('todos').on('value', (snapshot) => {
    var todos = [];
    snapshot.forEach((todo) => {
        todos.push(todo.val());
    });
    this.setState({
        todos: todos
    })
})

Upvotes: 5

Related Questions