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

191
Visualizações
Update property of hooks in another component

Here is a simplified version of my react code. I have a hook like this:

const [todo, setTodo] = useState();

My todo looks like this:

todo = {
    name: 'Name of my todo list',
    date: 2022-09-19',
    todos: [
        'groceries', 
        'do the laundry'
    ]
}

In my main component I pass to "todos component" the todos:

In my todos component, I have a loop on the props to show all input with todos value

{todos.map(t => {
   <input 
       value={t} 
       onChange={e => {
           t = e.target.value
       }} 
   />
})

But unfortunately it doesn't update the todo. How do I do this? I cannot use setTodo because I'm in the child component and setTodo manage all the todo object whereas I just want to update the list of todo. My component doesn't have knowledge of the full todo object but just the list of todo.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I cannot use setTodo

You must. That is the only way to change the state.

However, you don't necessarily need to use it directly in the child component. It makes total sense to want to limit the child component so it doesn't need to know about the entire todo object. To do this, you can pass down a function that knows how to do most of the update, and then have the child component call that, passing in the few pieces of information that the child is in charge of.

For example:

const Parent = () => {
  const [todo, setTodo] = useState();

  return (
    <Child 
      todos={todos} 
      onChange={(newValue, index) => {
        setTodo(prev => {
          const newArray = [...prev.todos];
          newArray[index] = newValue;
          return {
            ...prev,
            todos: newArray
          };
        });
      })
    />
  );
}

const Child = ({ todos, onChange }) => {
  // ...

  {todos.map((t, i) => {
    <input 
      value={t} 
      onChange={e => {
        onChange(e.target.value, i);
      }} 
    />
  })
}
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