0

hello i have a problem with my code i have function that filter the state of users (users is the state that contain all the users that added) but i need on the same onclick event that 1 i will delete the current object from the array (and i did it correctly)

2 to get this users and count all the number after the delete

but when i go to users forEach it not getting the updated state and get the old one only the second click will update.. so after deleteFlight function execute its update the users without the current number but when i start to use user.forEach it not give me the update state

  const [users, setUsers] = useState([]);
  const deleteFlight = (num) => {
    const afterFilter = users.filter((user) => {
      return user.numFlight !== num;
    });
    
     setUsers(afterFilter);
     alert("deleted")
  };
      <button
        onClick={() => {
          const inp = numFlightInp.current.value;

          deleteFlight(Number(inp));

          users.forEach((user) => {
            passengerCnt += user.passenger;
            totalFlightCnt++;
          });
          setFlightCnt2(totalFlightCnt);
          setPassengerCnt2(passengerCnt);

          if (!checkDuplicateFlight(Number(inp))) return alert("not found match");
        }}
      >
        delete
      </button>
Lior98
  • 79
  • 7
  • Flight and passenger count properly shouldn't be states at all. They should be *derived* from state, using `useMemo`. – Bergi Jul 12 '22 at 21:23
  • hey i am new to react can you explain it to begginer? or you can show me how it should be? i need them to be state because i need them to update on evrey click please guide me – Lior98 Jul 12 '22 at 21:43
  • `users` already updates on every click, right? Just count them every time you render. – Bergi Jul 12 '22 at 21:47
  • you mean by using useeffect the evrey render it will forEach on users? because i try iy and i have an issue with this solution when i go to this page of delete it start the useeffect because it on a diffrent componente but after i click delete it again run this useeffect and it mean that it double the result or that i aint using it right or that i didnt understand you correctly – Lior98 Jul 12 '22 at 21:58
  • 1
    I said `useMemo`, not `useEffect`. Or just no hook at all, put the `forEach` (and the var declarations) right after the `const [users, setUsers] = useState([]);`. – Bergi Jul 12 '22 at 22:08
  • first of all thank you so much for this solution and it worked! now i need to understand a few things the only change that i make is not use foreach on this deleteFlight compononte is to make the foreach on users at the App.js but! i try before to create a function and inside that function i create foreach and it still didnt work maybe it was because the counter was a state? – Lior98 Jul 12 '22 at 22:31

0 Answers0