0

I have data object as

let d = {
    'items': [
     {'item':'apple', price: 200},
     {'item':'banana', price: 300},
    ],
    tot:[2],
    'shop': 'xyx shop',
    'customer':['a','b','c']
    }

i am getting it from an api call and setting it to a state. Like this

const [state, setState] = useState({})

useEffect(
{
setState(d)
},[])

Here how can I update the price?

I have tried this

setState({...state, items[index].price - 1});

It's not working at all.

1 Answer 1

1
  1. Copy the items array from state
  2. Change the data
  3. Override the items array
let index = 1;
let newItems = [ ...state.items ];
newItems[index].price++;
      
setState({ ...state, items: newItems });

Example:

const {useState} = React;

const SameSet = () => {

    const [state, setState] = useState({
        'items': [
            {'item':'apple', price: 200},
            {'item':'banana', price: 300},
        ],
        tot: [ 2 ],
        'shop': 'xyx shop',
        'customer': ['a','b','c']
    });
    
    const update = () => {
     
      // Index to update
      let index = 1;
      
      // Copy
      let newItems = [ ...state.items ];
      
      // Bump
      newItems[index].price++;
      
      // Override
      setState({ ...state, items: newItems });
    }

    return (
        <div>
            <button onClick={update}>Click me to update!</button>
            {state.items.map(i => <em>{i.item}{' -- '}{i.price}</em>)}
        </div>
    )
}
ReactDOM.render(<SameSet />, document.getElementById("react"));
div { display: flex; flex-direction: column; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

technically, you are mutating item when you do newItems[index].price++;. when you create a copy from items array you still have the same old object references that array contains. you should create a new copy from the object you are updating with new price value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.