Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

323
Views
Storing an Array of Objects in Redux-Toolkit - Array is logging empty but it isn't

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!