Home > Blockchain >  React - Multiple Axios request
React - Multiple Axios request

Time:10-03

I am new to React and I was not able to find any solution for my problem. I am loading the first get request successfully then I take a random element from the array with lodash and with that info I can create a new URL but I am unable to create an array with the exact same method I have used for the first API call. Please someone could help me out how can I create a new axios.get request?

import axios from "axios";
import React from "react";
import _ from 'lodash';

export default function App() {

  const baseURL = "http://apiv3.iucnredlist.org/api/v3/region/list?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee";
  const [list, setList] = React.useState(0);
  const [error, setError] = React.useState(0);

  //get List of available regions
  React.useEffect(() => {
    axios.get(baseURL).then((response) => {
      setList(response.data);
    }).catch(error => {
      setError(error);
    })
  }, []);

  if (error) return `Error: ${error.message}`;
  if (!list) return null;

  //Take a random region from the list
  const randomRegion = _.sample(list.results);
  console.log(randomRegion)

  //Load the list of all species in the selected region
  const selectedRegion = "http://apiv3.iucnredlist.org/api/v3/species/region/"  randomRegion.identifier   "/page/0?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee"
  console.log(selectedRegion)

  const [speciesList, selectedRegionList] = React.useState(0);
  
  React.useEffect(() => {
    axios.get(selectedRegion).then((response) => {
      selectedRegionList(response.data);
    }).catch(error => {
      setError(error);
    })
  }, []);

  return (
    <div>
     
    </div>
  );
}

CodePudding user response:

You are using selectedRegion value before it is even initialized because an empty input in useEffect [] means that react will call it immediately after component has mounted. You need to make the second get request after the first one has been resolved or the component has updated (Lifecycle Methods) This can give a little more clarity
enter image description here

CodePudding user response:

here's the React way to do this

const App = () => {
  const [list, setList] = React.useState({});
  const [speciesList, setSpeciesList] = React.useState({});
  const [error, setError] = React.useState(0);
  const baseURL = "http://apiv3.iucnredlist.org/api/v3/region/list?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee";

  // get List of available regions
  React.useEffect(() => {
    function fetchdata() {
      axios
        .get(baseURL)
        .then(response => {
          const list = response.data
          setList(list); // got first list
          console.log(list)

          if (!list) return null;

          //Take a random region from the list
          const randomRegion = _.sample(list.results);
          console.log(randomRegion)

          //Load the list of all species in the selected region
          const selectedRegion = "http://apiv3.iucnredlist.org/api/v3/species/region/"   randomRegion.identifier   "/page/0?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee"
          console.log(selectedRegion)

          axios
            .get(selectedRegion)
            .then((response) => {
              const selectedRegionList = response.data
              setSpeciesList(selectedRegionList) // here'e data for the region
              console.log("data count:", selectedRegionList.count)
            }).catch(error => {
              setError(error);
            })

        })
        .catch(error => setError(error))
    }

    fetchdata()
  }, []);

  return <div / > ;
}

ReactDOM.render( < App / > , document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="root"></div>

  • Related