0

I am clicking on checkbox. When I am checking the checkbox I am trying to update state but it is not updating immediately. I have created an onchange event named handleAllCheckbox.

Here is my code - const [hello, setHello] = useState(false);

const handleAllCheckbox = (e) => {


    setHello(!hello);

    if (!hello) {
      contactList.map((item) => {
        Ids.push(item._id)
      });
      setTheArray(...theArray, Ids);
    }
    else {
      const newIds = []
      setTheArray(...theArray, newIds);
    }
  }

I want if hello is true then theArray must have Ids & if it is false then theArray should be empty.

1 Answer 1

1

You should be using useEffect if you want to handle any side effect, by side effect it means do something when a particular state change. So in your case probably can refer to below

import { useState, useEffect } from 'react';

const [hello, setHello] = useState(false);

useEffect(() => {
  if (!hello) {
    contactList.map((item) => {
      Ids.push(item._id)
    });
    setTheArray(...theArray, Ids);
  }
  else {
    const newIds = []
    setTheArray(...theArray, newIds);
  }
}, [hello]);


const handleAllCheckbox = () => setHello(!hello);

Notice [hello] as a second parameter of useEffect, it means do something whenever "hello" state is updated. So now your code is much cleaner as well, handleAllCheckbox only care about handling state hello, and whenever the value of hello being updated, useEffect takes care of that

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.