简体   繁体   中英

How to make a key value pairs and push it to state in React?

My desired output will look like this

{'3afdrjke3j43kjkjf' : 3 , '8fsdfdsni3ni3dsfa' :2 }

I tried like this but it didn't work

const [productQuantity, setProductQuantity] = useState([]);

    const handleQuantity = (e, id) => {
      setProductQuantity({id : e.target.value}) // this outputs {id : "3"}
    }

Whenever i trigger onchange event the id and and the quantity passed on the the handleQuantity function. Where i want to concat the key value pairs in to the state.

 <Form.Control onChange={(e) => handleQuantity(e, cartProduct._id)} as="select">
  {
   [...Array(cartProduct.quantity)].map((_, index) =>{
      return <option>{index + 1}</option>
    })
   }
 </Form.Control>

Thanks in Advance :)

You should store an object not an array in your state and merge that object with the new one onChange

// start with an empty object
const [productQuantity, setProductQuantity] = useState({});

const handleQuantity = (e, id) => {
  // merge existing state with new [id]: value pair
  setProductQuantity((currentQuantity) => ({
    ...currentQuantity,
    // don't forget the brackets here
    [id]: e.target.value,
  }));
};

To update the current state, pass a function to the setter

setProductQuantity(state => ({
  ...state,
  [ id ]: e.target.value
}))

This updates the existing state with a new property.

You should also initialise your state as an object if this is how you intend on using it

const [ productQuantity, setProductQuantity ] = useState({})

With out running your code I have an idea what the problem might be. You are doing this

  • setProductQuantity({id : e.target.value})

You need to set it in the array

  • setProductQuantity([id] : e.target.value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM