Home > Blockchain >  I want to call the API when I press the button
I want to call the API when I press the button

Time:12-29

When I press the button, I want the address in the API to be displayed on the screen under the button.

I have to write it in Next.js, but I don't know how to do it.

enter image description here

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { Button } from '@material-ui/core';

function TestPage() {
  console.log(process.env.NEXT_PUBLIC_WECODE_URI);

  const [state, setState] = useState('');

  const customFetch = async () => {
    const results = await axios
      .get(`${process.env.NEXT_PUBLIC_WECODE_URI}/testapi`)
      .then((res) => res.data?.results[0]?.address);
    setState(results);
  };

  useEffect(() => {
    customFetch();
  }, []);

  return (
    <>
      <Button
        variant="contained"
        color="primary"
        style={{ width: '200px' }}
        onClick={() => customFetch}>
        address
      </Button>
    </>
  );
}

export default TestPage;

CodePudding user response:

You want to set the state once the result has been obtained. The .then() in your axios call does nothing because this information is not returned - it is simply a callback of which you can handle the result in but since you are using async & await, the result is passed back to the variable you are assigning it to.

const customFetch = async () => {      
  const result = await axios.get(`${process.env.NEXT_PUBLIC_WECODE_URI}/testapi`);

  // If you want to set the state to the address
  setState(result.data?.results[0]?.address)

  // If you want to set the state to the full result
  setState(result)
}

Note that your useEffect() runs on mount and unmount of the component because of the empty dependency array []. This means that the customFetch function will run when the component is mounted and unmounted. I assume this is not the functionality you want since you have provided a button for this, so useEffect can be removed.

You also want to display the information. To do this, you can use the state like so...

return (
<>
  <Button
    variant="contained"
    color="primary"
    style={{ width: '200px' }}
    onClick={() => customFetch}>
    address
  </Button>
  <p>{state}</p>
</>

);

CodePudding user response:

you should call setState in .then(res => setState(res.data ...)) and in your component put "state" to display address. and actually you don't need to store axios in variable. just call axios in function and in "then block" call setState and store your result in state. in this scenario that you want to get the address with press button, you don't need to call customFetch() in useEffect. but if you want to get the address when page startup, you can use useEffect hook just like that.

  • Related