Reputation: 100
I have some datas, who I can get my data when I'm in the loop. But, if I set the data in a useState array value, I just have the last value.
How to get and show all the data in the render ?
My code out :
const [messagesList, setMessagesList] = useState([])
My code at useEffect :
firebase.database().ref(`accounts/${username}/messages/`).on('value', (snapshot) => {
const jsonData = snapshot.toJSON()
const keys = Object.keys(jsonData)
const finalData = keys.map(key => {
const element = jsonData[key]
for (const i in element) {
const elementFinal = element[i]
setMessagesList([elementFinal])
}
})
})
My code at render :
{messagesList.map((x, i) => (
<div key={i}>
<p key={i}>{x.senderUsername} said "{x.message}"</p>
</div>
))}
My Firebase database :
My result :
Upvotes: 1
Views: 36
Reputation: 108
You are erasing the value of messageList. Let say, elementFinal equals '45'
setMessagesList([elementFinal])
will result in
messagesList // ['45']
You need to read the previous value (the shallow copy is important) and set the new one:
const array = [...messagesList];
array.push(elementFinal);
setMessagesList(array)
EDIT: I didnt see that it could be reduced as follow:
const messages = [];
const finalData = keys.map(key => {
const element = jsonData[key]
for (const i in element) {
messages.push(element[i]);
}
})
setMessagesList(messages);
Upvotes: 1