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

175
Visualizações
How can I set State based on other state in functional component?

I build a simple todo app with a react with an array of todos:

const todos = [description: "walk dog", done: false]

I use the following two states:

  const [alltodos, handleTodos] = useState(todos);
  const [opencount, countOpen] = useState(alltodos.length);

This is the function which counts the open todos:

  const countTodos = () => {
    const donetodos = alltodos.filter((item) => {
      return !item.done;
    });
    countOpen(donetodos.length);
  };

When I try to add a new todo, I also want to update the opencount state with the countTodos function.

  const submitTodo = (event) => {
    event.preventDefault();

    const data = {
      description: todo,
      done: false,
    };

    handleTodos([...alltodos, data]);
    console.log(alltodos);
    countTodos();
  };

This does not work as expected, the when I run console.log(alltodos) it will show an empty array. The function itself works, but it seems to have a "delay", I guess based on the async nature of the useState hook.

I tried to pass the countTodos function as callback like this, since I have seen something similar in class based components.

handleTodos([...alltodos, data], () => {
  countTodos();
});

I get the following error:

Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().

How can I solve this problem? What is the best way for me to update the state based on another state?

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

0

I think you should useEffect, (clearly stated on the log message ). this is an example :

useEffect(()=>{
    const donetodos = alltodos.filter((item) => {
      return !item.done;
    });
    countOpen(donetodos.length);
   //countTodos();
},[alltodos]];

You can refer to the documentation : https://reactjs.org/docs/hooks-effect.html

Here is an example : https://codesandbox.io/s/react-hooks-useeffect-forked-4sly8

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