1

I'm making a pretty simple weather app using the open weather map API. The only responses I get are [object Object] when it's an axios call, [object Response] when I use fetch, [object Promise] when I console log res.json(). I get a successful GET message in the console. I'm pretty stuck now.

How can I access the object with the weather that's supposed to be returned?

Any help is appreciated.

const Weather = (props) => {

const [weather, setWeather] = useState({})
const [location, setLocation] = useState('')

const handleChange = event => {
 event.persist()

 setLocation(prevLocation => {
   // console.log(`previous ${prevLocation}`)
   // console.log(`target ${event.target.value}`)
   const updatedInput = { [event.target.name]: event.target.value }
   // console.log(`updated ${updatedInput}`)
   const createdLocation = Object.assign({}, prevLocation, updatedInput)
   // console.log(`created location ${createdLocation.toString()}`)
   return createdLocation.location
 })
}

console.log(`LOCATION = ${location}`)

const handleSubmit = (event) => {
 event.preventDefault()
 fetch(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${apiKey}`)
   .then(res => {
     console.log(`RES = ${res.json()}`)
   })
   .catch(console.error)
}

Also, if there's a better way to ask this question, I'll take some notes on that too.

jnr0790
  • 13
  • 3
  • Try to check what do you have in the `res` object in the browser console. (F12 on chrome). You should be able to inspect the whole object there. – diegocl02 Jul 02 '21 at 01:45
  • `res.json()` returns a **promise** that resolves with the parsed data structure – Phil Jul 02 '21 at 01:51

1 Answers1

1

You are getting the correct response, you just need to use the object properties to access the data. Try:

fetch(`https://api.openweathermap.org/data/2.5/weather? 
  q=${location}&appid=${apiKey}`)
  .then(res => res.json())
  .then(data=>setWeather(data.weather.main)
WebbH
  • 2,379
  • 1
  • 15
  • 26
  • The key difference here is that you are waiting for the `res.json()` promise to resolve – Phil Jul 02 '21 at 01:55