Reputation: 5
so I am trying to load all chat messages on page load. The messages are being retrieved just as I want them but I am having a horrible time trying to push all of them to state, I tried using loops etc but nothing seemed to work. This is the code:
const [name, setName] = useState("")
const [room, setRoom] = useState("")
const [messages, setMessages] = useState([])
const { room, name } = queryString.parse(location.search)
loadMessages(room).then((response) => {
if (response.error) {
console.log(response.error)
} else {
console.log(response)
setMessages([
...messages,
{ text: response.message, user: response.sender },
])
}
})
I just want to push every object in the response array into the messages state. Help greatly appreciated!
Upvotes: 0
Views: 57
Reputation: 8243
if the response is an array of messages, then you should map it and then set the state to it, like:
setMessages(response.map(item => ({
text: item.message,
user: item.sender
})
));
Ps: also as @George answered, also you should put the setMessages
on a useEffect(() => {}, [])
to prevent it to get datas on every update.
Upvotes: 1
Reputation: 3020
You need to use the useEfect
hook for data fetching.
The Effect Hook lets you perform side effects in function components
Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before.
https://reactjs.org/docs/hooks-effect.html
From your snippet, it would look something like this:
useEffect(() => {
const messages = async () =>
await loadMessages(room)
.then(response => {
if(response.error) {
console.log(response.error)
} else {
console.log(response)
setMessages([...messages,
{text: response.message,
user: response.sender}
]);
}
});
messages();
}, []);
Upvotes: 2