Home > Enterprise >  Get value from promise using React/Typescript
Get value from promise using React/Typescript

Time:07-15

I was given a snippet of a class named GithubService. It has a method getProfile, returning a promise result, that apparently contains an object that I need to reach in my page component Github.

GithubService.ts

class GithubService {
  getProfile(login: string): Promise<GithubProfile> {
    return fetch(`https://api.github.com/users/${login}`)
      .then(res => res.json())
      .then(({ avatar_url, name, login }) => ({
        avatar: avatar_url as string,
        name: name as string,
        login: login as string,
      }));
  }    

export type GithubProfile = {
  avatar: string;
  name: string;
  login: string;
};

export const githubSerive = new GithubService();

The page component should look something like this:

import { githubSerive } from '~/app/github/github.service';

export const Github = () => {
  let name = 'Joshua';
  const profile = Promise.resolve(githubSerive.getProfile(name));
  return (
    <div className={styles.github}>
      <p>
        {//something like {profile.name}}
      </p>
    </div>
  );

};

I'm pretty sure the Promise.resolve() method is out of place, but I really can't understand how do I put a GithubProfile object from promise into the profile variable. I've seen in many tutorials they explicitly declare promise methods and set the return for all outcomes of a promise, but I can't change the source code.

CodePudding user response:

You should wait for the promise to be resolved by either using async/await or .then after the Promise.resolve.

const profile = await githubSerive.getProfile(name);

const profile = githubSerive.getProfile(name).then(data => data);

CodePudding user response:

A solution would be:

import { githubSerive } from '~/app/github/github.service';

export async function Github() {
  let name = 'Joshua';
  const profile = await githubSerive.getProfile(name);
  return (
    <div className={styles.github}>
      <p>
        {profile.name}
      </p>
    </div>
  );
}

But if you are using react, things would be a little different (since you have tagged reactjs in the question):

import { githubSerive } from '~/app/github/github.service';
import * as React from "react";

export const Github = () => {
  let name = 'Joshua';
  const [profile, setProfile] = React.useState();

  React.useEffect(() => {
    (async () => {
       const profileData = await githubSerive.getProfile(name);
       setProfile(profileData);
    })();
  }, [])

  return (
    <div className={styles.github}>
      <p>
        {profile?.name}
      </p>
    </div>
  );
}

CodePudding user response:

as you are using React, consider making use of the useState and useEffect hooks.

Your Code could then look like below, here's a working sandBox as well, I 'mocked' the GitHub service to return a profile after 1s.

export default function Github() {
  const [profile, setProfile] = useState();

  useEffect(() => {
    let name = "Joshua";
    const init = async () => {
      const _profile = await githubService.getProfile(name);
      setProfile(_profile);
    };
    init();
  }, []);

  return (
    <>
      {profile ? (
        <div>
          <p>{`Avatar: ${profile.avatar}`}</p>
          <p>{`name: ${profile.name}`}</p>
          <p>{`login: ${profile.login}`}</p>
        </div>
      ) : (
        <p>loading...</p>
      )}
    </>
  );
}
  • Related