简体   繁体   中英

What to set useState to for a User type in React Hook

I'm new to hooks. Not sure what useState should be set to for the initial value.

Right now an empty object const [user, setUser] = useState({}); is set as the default value for useState and is causing ${crafter.id} to complain about id because there is no property id as it's trying to I guess use the default state for user which is set to {}.

UserProfile.tsx

interface UserProfileProps {
  userId: number;
  findUser: (userId: number) => Promise<User>;
}

const UserProfile = (props: UserProfileProps) => {
  const { userId, findUser } = props;
  const [user, setUser] = useState({});

  useEffect(() => {
    const fetchUser = async () => {
      const user: User = await findUser(userId);
      setUser(user);
    };

    fetchUser();
  }, []);

  return (<div>User Id: ${user.id}</div>);
};

export default UserProfile;

在此处输入图片说明

You should pass a generic parameter to useState so that TypeScript knows what the type of the value can be.

Also make sure only to try to get to the id property once the user has been retrieved, which can be done with optional chaining, and note that you don't need to type user as User , since findUser is already known to return Promise<user> :

const UserProfile = (props: UserProfileProps) => {
  const { userId, findUser } = props;
  const [user, setUser] = useState<User>(); // <---------------

  useEffect(() => {
    const fetchUser = async () => {
      const user = await findUser(userId);
      setUser(user);
    };

    fetchUser();
  }, []);

  return (<div>User Id: ${user?.id}</div>);
  // could also only return this div if the user has been retrieved,
  // and return an empty element instead, if you wanted
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM