Search code examples
reactjsreact-reduxreactstrap

object keeps resetting size into array after onClick


I'm trying to submit a form however, when i double submit again while changing the size value, it overrides the first object's selection. I'm using react-redux. I've tried using logic to select the correct value before passing the 2nd array. these are my codes.

    var roastedHazelnutLatte = {
    name:'Roasted Hazelnut Latte',
    size: 0,
    price:5,
    regularQty:0,
    oatlyQty:0,
    customisation: ''
} 

//drink size
const roastedHazelnutSize = e => {
    var{name,value} = e.target;
    var value = parseInt(value,10)
    roastedHazelnutLatte.size = value
}
//drink quantity
const roastedHazelnutRegularQty = e => {
    var {name,value} =e.target;
    var value = parseInt(value,10)
    roastedHazelnutLatte.regularQty = value
}
const roastedHazelnutOatlyQty = e => {
    var{name,value} = e.target
    var value = parseInt(value,10)
    roastedHazelnutLatte.oatlyQty = value
}
//drink customisation
const roastedHazelnutCustomisation = e => {
    const {name,value}=e.target;
    roastedHazelnutLatte.customisation = value
}
//on click add name of drink: hazelnut latte
const addHazelnutLatte = e => {
    e.preventDefault()
    addItem.orders.push(roastedHazelnutLatte)
    console.log(addItem)
}`

Dropdown codes:

<Input type='select' name='size' onChange={e=>roastedHazelnutSize(e)}>
    <option>Select</option>
    <option value={300}>300ml</option>
    <option value={1000}>1L</option>
</Input>

onClick codes:

<Button onClick={e=>addHazelnutLatte(e)}> Add</Button>

i'm thinking about setting state. but i'm not very sure how to go about it as well.


Solution

  • The reason the first object gets changed in the array is that the roastedHazelnutLatte object reference is always maintained even after you push it in array orders. You should update function to this

    const addHazelnutLatte = e => {
        e.preventDefault()
        addItem.orders.push({...roastedHazelnutLatte})
        console.log(addItem)
    }
    

    As an example

    const obj ={a: 1, b: 2}
    const arr = []
    arr.push(obj)
    obj.a = 5;
    arr.push(obj)
    console.log(arr) // would result [a: 5, b: 2}, a: 5, b: 2}]
    

    To fix this you can create a new object using ES6 spread operator, or, Object.assign but that's again would do a shallow copy on the object and not a deep copy.

    const obj ={a: 1, b: 2}
    const arr = []
    arr.push({...obj})
    obj.a = 5;
    arr.push({...obj})
    console.log(arr) // would result [a: 1, b: 2}, a: 5, b: 2}]