R
R
Ratibor Shugaev2022-02-01 19:07:54
typescript
Ratibor Shugaev, 2022-02-01 19:07:54

What's wrong with User types?

Good day. I study ts by analyzing various tasks found on the network. Tell me, what's wrong?
There is a code:

import React, { useState } from "react";

const URL = "https://jsonplaceholder.typicode.com/users";

type Company = {
  bs: string;
  catchPhrase: string;
  name: string;
};

type User = {
  id: number;
  email: string;
  name: string;
  phone: string;
  username: string;
  website: string;
  company: Company;
  address: any;
};

interface IButtonProps {
  onClick: any;
}

function Button ({ onClick }: IButtonProps): JSX.Element {
  return (
    <button type="button" onClick={onClick}>
      get random user
    </button>
  );
};

interface IUserInfoProps {
  user: User;
}

function UserInfo ({ user }: IUserInfoProps): JSX.Element {
  return (
    <table>
      <thead>
        <tr>
          <th>Username</th>
          <th>Phone number</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>{user.name}</td>
          <td>{user.phone}</td>
        </tr>
      </tbody>
    </table>
  );
};

function App(): JSX.Element {
  const [item, setItem] = useState<User[] | null>(null);

  const receiveRandomUser = async () => {
    const id = Math.floor(Math.random() * (10 - 1)) + 1;
    const response = await fetch(`${URL}/${id}`);
    const _user = (await response.json()) as User;
    setItem(_user);
  };

  const handleButtonClick = (
    event: React.MouseEvent<HTMLButtonElement, MouseEvent>
  ) => {
    event.stopPropagation();
    receiveRandomUser();
  };

  return (
    <div>
      <header>Get a random user</header>
      <Button onClick={handleButtonClick} />
      <UserInfo user={item} />
    </div>
  );
}

export default App;

and error

61f95a9a48688844618523.jpeg

It's not very clear which way to dig. Thank you for your responses!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2022-02-01
@ratibordas

useState<User[] | null >(null);

useState<User | null>(null);
And render UserInfo only if item != null

D
Dmitry Belyaev, 2022-02-01
@bingo347

useState<User[] | null>(null);
Here you write that in the state you have either null or an array of users.
const _user = (await response.json()) as User;
setItem(_user);
and here you persuaded TS that the answer is 1 user and you are trying to transfer it to the state.
interface IUserInfoProps {
  user: User;
}
and here your component also accepts only one user, but you pass it
<UserInfo user={item} />
value from state with typeUser[] | null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question