Search code examples
javascriptreactjsreact-hooksreact-state-management

React useState callback function not re-rnder DOM


I have a page for listing products in a table, each row of the table has checkbox who meant to toggle the row's active (Boolean) state when it clicked. The problem is that after updating the state the DOM doesn't change. This how my code looks like:

const [products, setProducts] = useState([]);

useEffect(() => {

    fetchProducts(); //fetch the products from the server

}, []);


const productChecked = (index) => { 
    setProducts((prevState) => {
        const newState = prevState;
        newState[index].active = !newState[index].active;
        return newState;
    });
};

...

{products.map((product, index) => {
    ...
    <td>
        <input type="checkbox" checked={!product.active} onClick={() => productChecked(index)}/>
    </td>
    ...
})}

I added this useEffect to test it, but it doesn't seem to work at all (I can't see this console log):

useEffect(() => {
    console.log('products',products);
}, [products]);

I can't understand why it is happening... what am I missing here?

Thanks in advance :)


Solution

  • To fix this issue, you should create a new copy of the products array before updating the state. You can do this by using the spread operator or slice method to clone the array. Here's the modified productChecked function:

      const productChecked = (index) => {
          setProducts((prevState) => {
            const newState = [...prevState]; // Create a new array copy
            newState[index].active = !newState[index].active;
            return newState;
          });
        };