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

125
Visualizações
How can I update state as an array of objects without overriding previous state

I want to update setTopic without overriding previous state. But I am getting topic is not iterable error.

What I tried? I tried looking a different examples on stack overflow, But still couldn't figure out how to append updated state without losing previous state.

Also, which is a better way to save multiple topics : an array of objects, simply objects or simply array?

const AddTopic = (props) => {
  const { subjectName } = props;
  const [topic, setTopic] = useState([
    {
      topics: [
        {
          id: Math.random().toString(36).substr(2, 7),
          topicName: "topic name",
          subject: subjectName,
        },
      ],
    },
  ]);

  const addTopicHandler = () => {

    setTopic(
      [...topic].map((item) => {
        return {
          ...item,
          id: Math.random().toString(36).substr(2, 7),
          topicName: "another topic name",
          subject: subjectName,
        };
      })
    );
  };
  console.log(topic);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  1. Instead of the child component using state lift the state to a parent component, and then just create dumb Topic components from the state.

  2. Rename your state. Call it topics, and the update function setTopics. Initialise it as an array, not an array containing one object containing an array.

  3. You can't immediately log an updated state. You need to use useEffect to watch for changes in state, and then log something.

const { useEffect, useState } = React;

// Topic component - just gets handed the
// subject (in this example) in the props
function Topic({ subject, category }) {
  return <div>{subject}: {category}</div>;
}

function Example() {

  // Initialise `topics` as an array
  const [ topics, setTopics ] = useState([]);

  // When `topics` is updated, log the updated state
  useEffect(() => console.log(JSON.stringify(topics)), [topics]);

  // Helper function that maps over the state and
  // produces an array of topics
  function getTopics() {
    return topics.map(topic => {
      const { subject, category } = topic;
      return (
        <Topic
          subject={subject}
          category={category}
        />
      );
    });
  }

  // Helper function to add a new topic object
  // to the topics state
  function addTopic() {
    const obj = { subject: 'Math', category: 'Fish' };
    setTopics([...topics, obj ]);
  }

  return (
    <div>
      <div>{getTopics()}</div>
      <button onClick={addTopic}>Add topic</button>
    </div>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Try to replace [...topic].map with [...topic.topics].map.

edit Sorry, I didn't see that the topic itself is an arr of objs, so it should be: [...topic[0].topics].map.

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