Search code examples
javascriptreactjsrenderingreact-functional-componentuse-state

React functional component is not rendering when updating the Sate after pushing data to array


I am trying to create a dynamic input form where user can add new inputs.

Problem

The component is not rendering when State is updated but when i open a Model that exists in the same component that is using a State to open/close it, all pushed elements in the array displayed at one time.

I didn't write the code of the Modal to make it easier to read the code

My Code

   const [supply_detail_list,setSupply_detail_list] = React.useState([
        {supplyDetail:'',supplyDetailAmount:''}
    ]);
    const addNewSuppDetailInput = () => {
        supply_detail_list.push({supplyDetail:'',supplyDetailAmount:''});
        setSupply_detail_list(supply_detail_list) 
    }

JSX

<div onClick={addNewSuppDetailInput}>+</div>
    {
        supply_detail_list.map((val,index) => {
            console.log('rendered')
            const detalTextID = 'supply_detail_text' + index;
            const detalValtID = 'supply_detail_val'+ index;
            return (
            <div className='supply-details'>
            •<input type='text' name={detalTextID} onChange={supply_detail_handler}/> <input className ='detail-value' onChange={supply_detail_handler} name={detalValtID} type='number'/>
            </div>
            );

        }) 
    }
    </div>

Solution

  • react expects you to return a new array when you want to update it instead of mutating it. Try something like this:

    const addNewSuppDetailInput = () => {
      setSupply_detail_list([
        ...supply_detail_list,
        { supplyDetail: '', supplyDetailAmount: '' },
      ]);
    };