Home > Back-end >  how can I use a variable inside a function, outside the function?
how can I use a variable inside a function, outside the function?

Time:12-22

Im trying to use my allData variable so i can use the data inside of it and show it in the return. Can someone help me on how can i use that variable inside of that fetchapi function outside of it.

that url (random-data-api) has an address, which i need to parse it somehow and print it in the return individually, im trying to use allData.address, also did fetchapi.allData.address. Im new in this, ive been doing research on how to do it, and i havent found something that helps


  const fetchapi = async () => {
    try {
      setLoading(true); // Antes del fecth
      await axios
        .get("https://random-data-api.com/api/v2/addresses")
        .then((response) => {
          setLoading(false); // loading false luego de mostrar la data
          const allData: Response = response.data;
          console.log(allData);
        });
    } catch (error) {
      setLoading(false); // loading false si sale un error
      console.log(error);
    }

    return allData;
  };

  return (
    <Fragment>
      <div>
        <button onClick={fetchapi}>Fetch Location</button>
        {address ? null : (
          <div
            style={{
              backgroundColor: "#c7c7c7",
              display: "flex",
              flexDirection: "column",
              padding: 16,
              margin: 5,
              borderRadius: 20
            }}
          >
            <p>
              <strong>Address: {Adress here from the allData var}</strong>
            </p>
            <p>
              <strong>City:{city here from the allData var}</strong>
            </p>
            <p>
              <strong>Street Name:{...}</strong>
            </p>
            <p>
              <strong>Zipcode:{...}</strong>
            </p>
          </div>
        )}
      </div>
    </Fragment>
  );

CodePudding user response:

You should declare a state for storing allData similar to how you did setLoading.

then you can store the response into state setAllData(response.data)

and use it in address field like allData.address

  • Related