Home > Enterprise >  Is there a way to create multiple counters using a state
Is there a way to create multiple counters using a state

Time:12-18

I tried to create a counter which is included in a mapped object so each time i click on the increment buttons it increase all the four counters at once meanwhile i want to use only three states: the counter, increase button and decrease button

 const [details, setDetails] = useState([
    {
    picture: Lantern,
    bookTitle: 'Quantitative Reasoning',
    school: 'Primary School',
      counter: 0,
    id: 1,
    increseBtn: 1,
  
  },
  {
    picture: Lantern,
    bookTitle: 'Quantitative Reasoning',
    school: 'Primary School',
    decrecreseBtn: '-',
    increseBtn: 2,
    price: 0,
    remove: 'Remove',
    id: 2
  
  },
  {
    picture: Lantern,
    bookTitle: 'Quantitative Reasoning',
    school: 'Primary School',
    decrecreseBtn: '-',
    increseBtn:3,
    remove: 'Remove',
    id: 3,
    counter: 0,
    
  },
  {
    picture: Lantern,
    bookTitle: 'Quantitative Reasoning',
    school: 'Primary School',
    decrecreseBtn: '-',
    increseBtn: 4,
    remove: 'Remove',
    counter: 0,
    id: 4,
    // increseBtn: {increase},
  
  },
  ]
  
  )


const increment = (id) => {
setcounter(counter 1)
}
const decrement = () => {
  setcounter(counter-1)
}
 <button  onClick={decrement}>-</button>
  <small>{counter} </small>
  <button onClick={()=> increment(add.id)}> </button>

CodePudding user response:

You can update by passing an id to the increment and decrement function

const increment = (id) => {
     setDetails(details.map(item => {
        if (item.id === id) {
           // Create a *new* object with changes
           return { ...item, counter: (item.counter ?? 0)   1 };
        } else {
          // No changes
          return item;
        }
    });

}
const decrement = (id) => {
     setDetails(details.map(item => {
        if (item.id === id) {
          // Create a *new* object with changes
          return { ...item, counter: (item.counter ?? 0) - 1 };
        } else {
          // No changes
          return item;
        }
     });
}

  // in the markup
  <button  onClick={() => decrement(add.id)}>-</button>
  <small>{add.counter} </small>
  <button onClick={()=> increment(add.id)}> </button>

You can read more about working with arrays in React Hope it helps

CodePudding user response:

Just set the counter for the objects where id matches after each increment and decrement operation.

details = details.map(obj => {
   if(obj.id === id) {
       obj = {
           ...obj,
           counter
       }
   }
   retrun obj;
})
  • Related