Home > Net >  React useState not updating on array splice
React useState not updating on array splice

Time:09-30

I have useState:

const [localImportedCustomers, setLocalImportedCustomers] = useState([]);

and template, to show the data:

<tbody>
{
    localImportedCustomers.map((value, index) => {
        return (
            <tr key={index}>
                <td>{index 1}</td>
                {
                    value.map((value1, index1) => {
                        return (
                            <td key={index1}>{value1}</td>
                        )
                    })
                }
                <td>
                    <button 
                        className="c-btn c-btn-danger"
                        onClick={ (e) => { deleteRow(e, index) } }
                    >
                        <FaTrash />
                    </button>
                </td>
            </tr>
        )
    })
}
</tbody>

trying to delete specific row, by below function:

const deleteRow = (e, index) => {
    e.preventDefault();
    let tmpArray = localImportedCustomers;
    tmpArray.splice(index, 1);
    setLocalImportedCustomers(tmpArray);
}

but template not updating, should someone has like this problem? Thanks for answers before the time!

CodePudding user response:

you are referencing same array. try spreding it so it actully create new array in memory.

    let tmpArray = [...localImportedCustomers];

CodePudding user response:

splice() modifies the array in-place instead of creating a new array. What this means is that you're setting state to the same array reference (even though its contents have changed), and React doesn't see that as an update to state.

Set state to a new array reference. Which could be as simple as this:

let tmpArray = [...localImportedCustomers];

This creates a new array and spreads the contents of the existing array into it. So when state is updated, the array reference itself has changed and React sees it as new state.

  • Related