Solution 1 :

You forgot about the names field when updating the state. Simply include it using e.g. object destructuring.

setCustomerState((prevState) => ({
   ...prevState,
   pickedName: namePool[number],
}));

You app crashes in the line namePool[number] since namePool (customerState.names) is undefined.

const Customer = () => {
  const [customerState, setCustomerState] = useState({
    names: ['Martin', 'Andrea', 'Carol'],
    pickedName: 'Martin',
  });

  const switchName = () => {
    const namePool = customerState.names;
    const number = Math.floor(Math.random() * 3);

    setCustomerState((prevState) => ({
      ...prevState,
      pickedName: namePool[number] as string,
    }));
  };

  return (
    <div>
      <h2>Customer:</h2>
      <h3>{customerState.pickedName}</h3>
      <button onClick={switchName}>Change name</button>
    </div>
  );
};

Solution 2 :

@kind user made me think and i came up with solution.

As he mentioned names must be defined again because switchName overrides useState so i have changed:

setCustomerState({pickedName: namePool[number]});

into

setCustomerState({names: namePool, pickedName: namePool[number]});

and it’s all working fine now.

Problem :


I am following some Reactjs course and faced issue which seems not to appear in this course..

Customer.js:

import React, { useState } from "react";

const Customer = () => {

    const [customerState, setCustomerState] = useState(
        {
            names: ['Martin', 'Andrea', 'Carol'],
            pickedName: 'Martin'
        }
    );

    const switchName = () => {
        const namePool = customerState.names;
        const number = Math.floor(Math.random()*3); //losowanie liczby w zakresie 0-2
        setCustomerState({pickedName: namePool[number]});
    }

    return(
        <div>
            <h2>Customer:</h2>
            <h3>{customerState.pickedName}</h3>
            <button onClick={switchName}>Change name</button>
        </div>
    );
}

export default Customer;

Mentioned code gives me error for line setCustomerState({pickedName: namePool[number]});:

enter image description here

and in Browser console i can see:

enter image description here

Comments

Comment posted by gipcu

I’m sorry, i’m pretty new in React, could you expand your answer? how code should look like?

Comment posted by gipcu

copy-paste, and got same error:

Comment posted by kind user

@gipcu I posted whole component. It doesnt throw any errors

Comment posted by gipcu

no idea why this does not work for me.

Comment posted by kind user

@gipcu Updated my answer – please check it. Just copy my code and paste in your editor.

Comment posted by kind user

“names must be defined”

By