1

I want to increment the counter value of an item on click, I've tried to find the solution in the docs and I watched tutorials but I can't find the solution.

FruitCounter.js

import { Fragment, useState } from "react"
import Fruit from "./Fruit"

const data = [
    { id: 1, name: "🍋", counter: 0 },
    { id: 2, name: "🍒", counter: 0 },
]

const FruitCounter = () => {
    const [fruits, setFruits] = useState(data)

    const clickHandler = (fruit) => {
       // Increment 'counter value of clicked item by 1'
    }

    return (
        <Fragment>
            {fruits.map((fruit) => {
                return (
                    <Fruit
                        key={fruit.id}
                        {...fruit}
                        clickHandler={() => clickHandler(fruit)}
                    />
                )
            })}
        </Fragment>
    )
}

export default FruitCounter

Fruit.js

import React from "react"

const Fruit = ({ counter, name, clickHandler }) => {
    return (
        <button type="button" className="fruit" onClick={clickHandler}>
            <p>{counter}</p>
            <h2>{name}</h2>
        </button>
    )
}

export default Fruit
0

1 Answer 1

1

You can try this

  const clickHandler = (fruit) => {
    setFruits(
      fruits.map((x) => {
        if (x.id === fruit.id)
          return {
            ...x,
            counter: x.counter + 1,
          };
        return x;
      })
    );
  };
Sign up to request clarification or add additional context in comments.

2 Comments

As state updates may be asynchronous: setFruits((prevFruits) => prevFruits.map.....
@AjeetShah In general you are right, but inside click handler, when you don't have multiple setState calls, most of the times you will always read fresh state anyway.

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.