'Render Previous State in React with Redux

I'm trying to build a 10 Pin Calculator in React with Redux and I'm trying to show my recently clicked on number to the tables:

It's kind of hard to explain with plain text so I thought I'd show with some examples:

Initial State Here is my initial state which is always on 0, and whenever I click any of the numbers above from 1 to 10, it updates: Updated State But what I want is that for each time I click on a number, the number I've clicked on will be rendered on each Player row, so for example like this (Now this example below is hardcoded):

Hardcoded Example

I thought about using an array and for each time I click on a number, the number is pushed to the array but it didn't work and I tried debugging it with no findings whatsoever on why it didn't work:

export const AddScore = () => {
  const count = useAppSelector((state) => state.scores.value);
  const dispatch = useAppDispatch();
  const [playerScoreArray, updatePlayerScoreArray] = useState<number[]>([
    1, 5, 10,
  ]);

  const onClick = (i: number) => {
    dispatch(increaseScoreByAmount(i + 1));
    console.log(i + 1);
    updatePlayerScoreArray( i => [...i]);
  };

  return (
    <>
      <div className="py-5">
        {[...Array(10)].map((e: number, i: number) => {
          return (
            <Button onClick={() => onClick(i)} variant="outlined" key={i + 1}>
              {i + 1}
            </Button>
          );
        })}
      </div>
      <Scoreboard playerScore={playerScoreArray} maxScore={count} />
    </>
  );
};

The playerScoreArray is rendered in another component Scoreboard where I'm trying to map through the array to display them for each Player but I figured that wouldn't work.

<tbody className="bg-white divide-y divide-gray-200">
                {/* Info Here */}
                <tr>
                  {playerScore.map((scores) => (
                    <td
                      className="px-6 py-4 whitespace-nowrap"
                      key={Math.random()}
                    >
                      {scores}
                    </td>
                  ))}
                  <td className="px-6 py-4 whitespace-nowrap">{maxScore}</td>
                </tr>
              </tbody>

I tried using a normal array then an array with useState but nothing worked.

Is there any way to do this with Redux?

Thanks in advance for any help



Solution 1:[1]

I finally found a solution, here it is:

  const onClick = (i: number) => {
    dispatch(increaseScoreByAmount(i + 1));
    if (playerScoreArray.length < 10) {
      // This below is the solution
      updatePlayerScoreArray((playerScoreArray) => [
        ...playerScoreArray,
        i + 1,
      ]);
    }

  };

This allowed me to push to my useState array from every Redux click.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NMNamu