Answer the question
In order to leave comments, you need to log in
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;
Answer the question
In order to leave comments, you need to log in
useState<User[] | null >(null);
useState<User | null>(null);
useState<User[] | null>(null);
Here you write that in the state you have either null or an array of users.and here you persuaded TS that the answer is 1 user and you are trying to transfer it to the state.const _user = (await response.json()) as User; setItem(_user);
and here your component also accepts only one user, but you pass itinterface IUserInfoProps { user: User; }
<UserInfo user={item} />
value from state with typeUser[] | null
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question