Home > Software design >  React useEffect is not getting triggered
React useEffect is not getting triggered

Time:05-22

Here is my code:

state initialization

const [uncheckedColArr, setUncheckedColArr] = useState([]);

Control is reaching to the following function, and also consoling correctly.

const updateFilterValue = (columnName, fieldValue, checked) => {
    let tempUncheckedColArr = uncheckedColArr;
    if (tempUncheckedColArr[columnName] === undefined) {
        tempUncheckedColArr[columnName] = [];
    }
    tempUncheckedColArr[columnName] = _.xor(
        tempUncheckedColArr?.[columnName],
        [fieldValue]
    );
    console.log("uncheckedColArr1", uncheckedColArr);

    setUncheckedColArr(tempUncheckedColArr);
    console.log("tempUncheckedColArr", tempUncheckedColArr);
    console.log("uncheckedColArr2", uncheckedColArr);
};

But, it's not triggering following useEffect whenever unCheckedArr is updated from above function

useEffect(() => {
    console.log("uncheckedColArr", uncheckedColArr);
    uncheckedColArr.map((col) => {
        console.log("col", col);
    });
}, [uncheckedColArr]);

CodePudding user response:

The way you are updating your array is incorrect:

const updateFilterValue = (columnName, fieldValue, checked) => {


    let tempUncheckedColArr = [...uncheckedColArr]; //<=== this will create new array
    if (tempUncheckedColArr[columnName] === undefined) {
        tempUncheckedColArr[columnName] = [];
    }
    tempUncheckedColArr[columnName] = _.xor(
        tempUncheckedColArr?.[columnName],
        [fieldValue]
    );
    console.log("uncheckedColArr1", uncheckedColArr);

    setUncheckedColArr(tempUncheckedColArr);
    console.log("tempUncheckedColArr", tempUncheckedColArr);
    console.log("uncheckedColArr2", uncheckedColArr);
};

CodePudding user response:

Can you try to copy uncheckedColArr without referance save?

let tempUncheckedColArr = [...uncheckedColArr];
  • Related