Reputation: 65
I am using firebase and react. I am mapping through the database trying to assign a key to each item. I've done this before and had no problems but for some reason, React doesn't like it. I using componentDidMount to sync my app to firebase and this is where I'm grabbing each item and the unique key from firebase. Also, console.log gives me the correct key I want.
componentDidMount() {
this.todosRef.on('child_added', snapshot => {
const todo = snapshot.val();
todo.key = snapshot.key;
console.log(todo.key);
this.setState({ todos: this.state.todos.concat( todo ) });
});
}
but when I map through the array and assign the key it throws the error : Cannot create property 'key' on string '
Here is how I am mapping:
const listOfTodos = this.state.todos.map( (todo) => {
return <li key={todo.key}>{todo}</li>
});
Upvotes: 4
Views: 7399
Reputation: 2806
I believe what you have is an immutable object which you're trying to modify.
https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot
A DataSnapshot is an efficiently generated, immutable copy of the data at a Database location. It cannot be modified and will never change (to modify data, you always call the set() method on a Reference directly).
Try putting your todo and key into a new object like this:
const todo = { key: snapshot.key, value: snapshot.val() }
Upvotes: 5