Search code examples
reactjssetstate

setState is not reRendering ReactJS


prevArray is my old array without a status property or values. Response is from the backend. I can see that the array is being set with the new value by inspecting the web and looking in the components section. I can delete an item in the array

       const [data,setData] = useState([]);
                    

        OrderFinder.put("/orderss",{
            sent:"success",
            data:array        
        }).then((response) => {updateStatus(response.data,array)})
        .catch(err => console.log(err))
    }

     const updateStatus = (response,array) => {
       for(const obj in array){
        for(const order in response.orders){
            if(array[obj].Name === response.orders[order].name.replace("#", "")){
                array[obj].Status = response.orders[order].Status;
                break;
            }
        }
    }
    const newArray = array;
    setData(newArray);
}

Solution

  • I believe you are setting the same link to the array to your state, that's why React doesn't track your changes. Try to create a new array using a spread operator:

        const newArray = [...array];
        setData(newArray);
    

    Explanation: non-primitive values (objects, arrays) in JS assigned by a link, it means if you assign one array to 2 variables these variables will be the same, as they referring to the same array (you could read it in more details here)