I am using Redux-Toolkit on React.
I am trying to store an array of objects in my redux store that will be a list of chat messages.
Here is my clientSlice.js (where my actions are created)
export const clientSlice = createSlice({
name: 'client',
initialState: {
messages: []
},
reducers: {
//Add message to list of messages
setAddMessage: (state, action) => {
state.messages.push(action.payload);
}
},
});
I am able to add objects to the array using useDispatch(setAddMessage(message))
In my messages.js I am able to map the messages onto my HTML like so:
const messages = useSelector(selectMessages);
{messages ? (
[...Object.values(messages)]
.sort((a, b) => a.time - b.time).map((message) => (
<div
key={message.id}
className="message-container"
>
<span className="message-user">{message.user}</span>
<span className="message-content">{message.value}</span>
<span className="message-date">{new Date(message.time).toLocaleTimeString()}</span>
</div>
))
) : (<div></div>)}
Works fine... my messages show up on the front end.
However, my issue arises when I try and console.log(messages) from my Messages.js file. I get the response:
Array []
length: 0
<prototype>: Array []
Even though my messages are continuing to appear from mapping "messages"... it logs length 0.
Also, If I try to do something like
console.log(messages[1])
-undefined
What am I missing here guys?
Hi you should change the selector tag in your messages.js to this
const count = useSelector((state) => state.name)
Where name is the name of reducer of your redux config