Hemanth
Hemanth

Reputation: 151

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 :)

Upvotes: 3

Views: 7495

Answers (3)

Joe Gleiter
Joe Gleiter

Reputation: 13

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)

Upvotes: 0

hiddenuser.2524
hiddenuser.2524

Reputation: 4988

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,
  }));
};

Upvotes: 3

Phil
Phil

Reputation: 164731

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({})

Upvotes: 1

Related Questions