Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

329
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda