Search code examples
javascriptreactjsfetch

Can't get multiple data from API using foreach loop with Fetch API get request


In my project, I need to get organization data's from api firstly, then ı need to get another specific data's from another api with sending as a parameter organizationEIC property of my organization data which ı get in first request. I can get the organization datas successfully and set them to items state successfully. But when ı came to the second API request which made in getPlants() method, my program and my RAM fail and ı get net::ERR_INSUFFICIENT_RESOURCES error for each request. I just put the incoming data to the datas array in order not to setState every time and to prevent the component from rendering again, but the program still crashes. I got some solutions with using hooks but I'm beginner in react and ı don't have any knowledge about hooks and want to solve this issue with basic react to develop myself better.

state = {
    items: [],

    plants: []
  } 

componentDidMount() {
    fetch('https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-organization', {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        'X-Requested-With': 'XMLHttpRequest'
      }
    })
      .then(response =>
        response.json())
      .then(resultJson => {
        this.setState({
          items: resultJson.body.organizations,      //can get successfully and set state items ok.
        })
        
      });
  }

getPlants = () =>{
    this.state.items.forEach((plant) => {            //foreach loop with using items state
      fetch(`https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-injection-unit-name?organizationEIC=${plant.organizationETSOCode}`, {
        method: 'GET',
        headers: {
          "Content-Type": "application/json",
          'X-Requested-With': 'XMLHttpRequest'
        }
      })
        .then(response => response.json())
        .then(resultJson => {
          datas.push(resultJson.body.injectionUnitNames)     //where ı fail
        })
    })
  }

  render() {
    this.getPlants()           //just necessery part of render method
    console.log(datas)

THX in advance for your help and suggestions


Solution

  • (1) This probably happened because you are calling .getPlants() on every render. You should probably call getPlants inside componentDidMount instead.

    (2) You may use promise.all to speed up your fetch.

    getPlants = async (items) =>{
    
    const data = await Promise.all( items.map((plant) => {
         return fetch(`https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-injection-unit-name?organizationEIC=${plant.organizationETSOCode}`, {
        method: 'GET',
        headers: {
          "Content-Type": "application/json",
          'X-Requested-With': 'XMLHttpRequest'
        }
      }).then(response => response.json())
    }))
    
    this.setState({ data })
    }
    

    ComponentDidMount

    componentDidMount() {
        fetch('https://cors-anywhere.herokuapp.com/https://seffaflik.epias.com.tr/transparency/service/production/dpp-organization', {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            'X-Requested-With': 'XMLHttpRequest'
          }
        })
          .then(response =>
            response.json())
          .then(async resultJson => {
            this.setState({
              items: resultJson.body.organizations,      //can get successfully and set state items ok.
            })
            await getPlants(resultJson.body.organizations) // we call get plants here
            
          });
      }