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

174
Views
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 answers
Answer question

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 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!