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.

2
  • 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. Commented Jul 2, 2021 at 1:45
  • res.json() returns a promise that resolves with the parsed data structure Commented Jul 2, 2021 at 1:51

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

The key difference here is that you are waiting for the res.json() promise to resolve

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.