Ibrahim Ch
Ibrahim Ch

Reputation: 23

how to update specific index of integer array in functional component setState in react js

first i make price int array and store int numbers in hook only once then i want to update specific index of that price array in update value but didnt able to update setPrice specific index instead it return me to array with only one value but i want all values with updated index value like [0,3,4,5,6] update id 1 then in my logic multiply by 2 it should do [0,6,4,5,6] but it return me only [6]

import React, {useEffect,useState,useContext } from 'react';
import {Cartlist} from '../Global/CartContext.js';
const Cart=()=>{
  const {ShoppingCart,totalprice,quantity,dispatch} = useContext(Cartlist);
  const [price,setPrice]=useState([])
  const Style={
    width:'100px',
    height: '100px',
  }
  useEffect(()=>{
    ShoppingCart.map((products)=>{
      setPrice(prev=>[...prev,products.price]);
    })
  },[])
  const updatevalue=(e)=>{
    ShoppingCart.map((products)=>{
      if (e.target.id===products.id){
          setPrice(price=>price[products.id-1]*2);
      }
  })
  }
  return (
    <div className='container'>
      {ShoppingCart.length > 0 ?
        ShoppingCart.map((products)=>(
          <div>
            <span><img style={Style} src={products.image}></img></span>
            <span>{price}</span>
            <span>{quantity}</span>
            <span><button id={products.id} onClick={updatevalue}>+</button></span>
          </div>
        ))
      :''}
    </div>
  )
}
export default Cart

Upvotes: 2

Views: 2498

Answers (1)

Drew Reese
Drew Reese

Reputation: 202916

You can simply pass the index to the updatevalue when the cart is mapped, and update the price array at that index. convert updatevalue to a curried function to consume the index and return the event handler.

const updatevalue = index => () => {
  setPrice(prices => prices.map((price, i) => i === index ? price * 2 : price));
}

...

return (
  <div className='container'>
    {ShoppingCart.map((products, i)=>( // <-- cart index
      <div>
        <span>
          <img style={Style} src={products.image} />
        </span>
        <span>{price}</span>
        <span>{quantity}</span>
        <span>
          <button onClick={updatevalue(i)}>+</button> // <-- pass index to handler
        </span>
      </div>
    ))}
  </div>
)

Upvotes: 1

Related Questions