Home > Enterprise >  Why does useEffect doesn't update state on element delete
Why does useEffect doesn't update state on element delete

Time:10-07

i have no idea why useEffect working like this, when updating state and adding items in SearchData(useState) it's working correctly and updating state but when i'm deleting element from SearchData, useEffect doesn't trigger.

main function

const tableSearch = (e) => {
    let value = e.currentTarget.value;
    let input = e.currentTarget;
    let mainData = props.data;
    let itemKey = e.currentTarget.parentNode.parentNode.id;
    if (input.checked) {
      addEl(mainData, itemKey, value);
    }
    if (!input.checked) {
      deleteEl(itemKey, value);
    }
  };
  

add element (this working correclty)

 //add element on check
  const addEl = (mainData, itemKey, value) => {
    for (let i = 0; i < mainData.length; i  ) {
      if (mainData[i][itemKey] !== null && mainData[i][itemKey].includes(value)) {
        tempData.push(mainData[i])
      }
    }
    if(searchData){
        let tempArr = tempData.concat(searchData)
        setSearchData(tempArr)
    }else{
        setSearchData(tempData)
    }
    
  };

problem is here (delete element)

 //delete element on uncheck
  const deleteEl = (itemKey, value) => {
    for (let i = 0; i < searchData.length; i  ) {
      if (searchData[i][itemKey].includes(value)) {
          console.log(searchData[i][itemKey])
        let index = searchData.indexOf(searchData[i]);
        searchData.splice(index, 1);
      }
    }
    setSearchData(searchData);
  };

  useEffect(() => {
    if (searchData) {
      setData(searchData);
    pagination();
    }
  }, [searchData]);

CodePudding user response:

You can't update state like that (on your deleteEl function). Use a temporary variable like you did on your addEl function, and then update state using that. Something like

const deleteEl = (itemKey, value) => {
    let tempArr = searchData
    for (let i = 0; i < tempArr.length; i  ) {
      if (tempArr[i][itemKey].includes(value)) {
          console.log(tempArr[i][itemKey])
        let index = tempArr.indexOf(searchData[i]);
        tempArr.splice(index, 1);
      }
    }
    setSearchData(tempArr);
  };

CodePudding user response:

you can't do like that on searchData (searchData.splice) you can set it with setSearchData only

const deleteEl = (itemKey, value) => {
    setSearchData(data=>{
        for (let i = 0; i < data.length; i  ) {
            if (data[i][itemKey].includes(value)) {
                console.log(data[i][itemKey])
                let index = data.indexOf(data[i]);
                data.splice(index, 1);
            }
        }
        return data;
   })
};
  • Related