Home > Back-end >  How can I retrieve JSON after getting a response from another JSON (React.js)
How can I retrieve JSON after getting a response from another JSON (React.js)

Time:07-05

Hopefully, the question title isn't too vague or confusing, but I will explain it here:

Basically, I am trying to learn more about APIs during my React.JS journey. The project is to obtain Weather Forecast info based on whatever location (I am doing it based on Postal Codes in Canada) you enter in the search box. I am using Axios specifically for this one, and I've come across a little problem.

I want the program to take the response from one API link, and then take specific data from that response to insert it into another API link. Then it will finally get the response from the new link. Hopefully, this isn't confusing as well. I tried different things, and still no luck, but I will put what I have tried recently below.

Here's what I did so far:

import React, { useState } from 'react'
import axios from 'axios'

function App() {
  
  // UseStates to change the variables
  const [data, setData] = useState({})
  const [postalcode, setPostalCode] = useState('')
  const [latitude, setLatitude] = useState(0)
  const [longitude, setLongitude] = useState(0)

  // API Links
  const geocodingURL = `http://api.openweathermap.org/geo/1.0/zip?zip=${postalcode},CA&limit=1&appid=7fe57d3d219cd9512845e116e4c353c5`
  const weatherURL = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=7fe57d3d219cd9512845e116e4c353c5`
  
  // Arrow Functions to retrieve the responses from the API Links
  const searchPostalCode = (event) => {
    if (event.key === 'Enter') {
      axios.get(geocodingURL).then((response) => {
        setData(response.data)
        console.log(response.data)
      })

      axios.get(weatherURL).then((response) => {
        setLatitude(data.lat)
        setLongitude(data.lon)
        setData(response.data)
        console.log(response.data)
      })

      setPostalCode("")
    }
  }

  return (
    <div className="app">
      <div className="search">
        <input
          value={postalcode}
          onChange={event => setPostalCode(event.target.value) && setLatitude(data.lat) && setLongitude(data.lon)}
          onKeyPress={searchPostalCode}
          searchWeather
          placeholder='Enter Postal Code'
          type="text"/>
      </div>

      <!-- There is more code here, but I don't think it's necessary for this question since it's just header tags -->
    </div>
  );
}

export default App;

The Weather API I'm using doesn't have a direct Location -> Weather API. I have to use two, so I have to do Location -> Longitude & Lattitude, and then Longitude & Lattitude -> Weather.

If what I said is confusing, please let me know. I can try to explain it more if needed.

Also, since I'm kinda new to this whole React.js and API thing, if there are any tips you would recommend, let me know. I would love to know any useful info throughout this journey.

Thanks!

CodePudding user response:

By dragging the second axios request inside the then of the first request, so you can use the response of the first request.

Or you can use async and await syntax.

For more resources.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

CodePudding user response:

  axios.get(geocodingURL).then((geoCodingRes) => {
    // next call
    axios.get(weatherURL).then((weatherREs) => {
        // set your react states here
    })
  })
  • Related