I'm having some trouble trying to change specific button's value when clicked and get back to the previous value with setTimeout()

Viewed 22

Here's my example code (I'm trying in a separated component with different Data.

import React, { useState } from 'react';

const initialState = [
  { id: 0, text: 'add to cart' },
  { id: 1, text: 'add to cart' },
  { id: 2, text: 'add to cart' },
];

const Test: React.FC = () => {
  const [text, setText] = useState(initialState);

  const handleClick = (index: number) => {
    const newText = [...text];
    newText[index].text = 'Added to cart...';
    setText(newText);

    setTimeout(() => {
      setText(initialState);
    }, 2000);
  };

  return (
    <div>
      {text.map((buttons, index) => (
        <button key={index} onClick={() => handleClick(index)}>
          {buttons.text}
        </button>
      ))}
    </div>
  );
};

export default Test;
1 Answers

You should deep clone your array with JSON.parse(JSON.stringify(...)) since you are editing nested properties.
This code should work:

const handleClick = (index: number) => {
  const newText =  JSON.parse(JSON.stringify(text));
  newText[index].text = 'Added to cart...';
  setText(newText);

  setTimeout(() => {
    setText(initialState);
  }, 2000);
};
Related