Home > Blockchain >  Reactjs &Typescript: how to show result from API call?
Reactjs &Typescript: how to show result from API call?

Time:10-03

I want to show result of API call in reactjs & typescript. In the following code, first segmentation is the API call and the second segmentation is for show result in the UI. Both segmentation are in one file:

First segmentation:

  const upload = React.useCallback(async () => {
        try {
          const response = await mymethod(
           
            user,
            pass,
            onUpload
          );
          setSuccess(true);
          setUploading(false);
         
          return { body: response.data};    
        }              
      }, [
        pass,
        user,       
      ]      
      );

second segmentation:

  return (
        <AuthLayout showInfo={true}>
          <div className={classes.root}>                
              <Container>
                <Box
                  display="flex"
                  flexDirection="column"
                  alignItems="center"                    
                >
                  {uploading ? (
                    <>
                      <BorderLinearProgress
                        variant="determinate"
                        value={progress}
                      />
                    
                    </>
                  ) : success ? (
                    <>
                      <CheckCircleOutline
                        className={classes.successIcon}
                        fontSize="inherit"
                      />        
                      <div>
                      **// I want to show result of call API here**
                    </div>                        
    
                    </>
                  ) : (
                    <>                         
                   
                    </>
                  )}
                </Box>
              </Container>
            </Box>
          </div>
        </AuthLayout>
      );   

How to show result of the API call ( return { body: response.data}; ) in the second segmentation? response.data is a json with following key: message & validity.

Thank you for your attention....

CodePudding user response:

To put it simply... You'd do the same thing you're already doing with other values. Notice how you have state values presumably declared like this:

const [success, setSuccess] = useState();

And you set the values in your API call:

setSuccess(true);

And you read the values in your rendering.

So what you'd do to use the values from your API call is... declare your state, set your state, read your state. Same thing. For example:

const [apiResult, setAPIResult] = useState();

And:

setAPIResult(response.data);

And in the render, perhaps something like:

{
  apiResult ? (
    <>
      render values from apiResult in this markup
    </>
  ) : null
}
  • Related