reactjsreact-hooksupdating

React useState not updating on array splice


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!


Solution

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

        let tmpArray = [...localImportedCustomers];