gipcu
gipcu

Reputation: 321

Reactjs - Argument type is not assignable to parameter type


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

Upvotes: 2

Views: 874

Answers (2)

gipcu
gipcu

Reputation: 321

@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.

Upvotes: 0

kind user
kind user

Reputation: 41893

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>
  );
};

Upvotes: 2

Related Questions