Home > Mobile >  Save to state unknown input count
Save to state unknown input count

Time:07-16

I get data from database and map them but I dont know the count of inputs, every time can be different. So I need to get all data from inputs to one array in useState and save his value and his id.

const [filteredValuesSlider, setFilteredValuesSlider] = React.useState([{value:'', product_id:''}]);


const changeFilteresValuesFromSlider = (value, product_id) =>{
    setFilteredValuesSlider((prevValues) => [ ... prevValues, {value:value, product_id:product_id}]);
    console.log(filteredValuesSlider);
  }


  {filterListDataName && ( 
    filterListDataName.map((item, index) => {
          return (
                <div className='mt-1 form-content'>
                  <input type="text" placeholder={"insert number"} onChange={(e) => changeFilteresValuesFromSlider(e.target.value, item.id)}/>
                </div>
          );
        }))}

Now Im getting this in console

(5) [{…}, {…}, {…}, {…}, {…}]
0: {value: '', product_id: ''}
1: {value: '1', product_id: '26'}
2: {value: '15', product_id: '26'}
3: {value: '1', product_id: '25'}
4: {value: '10', product_id: '25'}
length: 5

but I need to get data like

(2) [{…}, {…}]
0: {value: '15', product_id: '26'}
1: {value: '10', product_id: '25'}
length: 2

CodePudding user response:

You're always appending to the array, regardless of what's in it already:

setFilteredValuesSlider((prevValues) => [ ... prevValues, {value:value, product_id:product_id}]);

If you want it to over-write any existing matching value, filter out matching values when appending:

setFilteredValuesSlider((prevValues) => [
  ...prevValues.filter(v => v.product_id !== product_id),
  {value:value, product_id:product_id}
]);
  • Related