0

I'm quite new to React and I'm trying to get a response from weatherapi.com. However I haven't been very successful. The following is my code snippet:

const api_call = async () => {
    const url = 'https://api.weatherapi.com/v1/current.json?key=' + API_KEY + '&q=Singapore'
    const request = axios.get(url)
    const response = await request
    console.log('url - ' + url)
    console.log('request - ' + request)
    console.log('response - ' + response)
}
useEffect(() => {
    api_call()
}, [])

the console log that was printed (i had to redact the API Key) :

url - https://api.weatherapi.com/v1/current.json?key=xxxxxxxxxx&q=Singapore 
request - [object Promise] 
response - [object Object]

I went to the link next generated, and it did show the data I want in the browser.

My axios version is 0.21.1 if it helps.

Now, I want the response to be printed in the console just so I can make sure that I actually got the response. Did I miss something? Thanks beforehand.

4 Answers 4

1
   const api_call = async () => {
    try {
      const url =
        "https://api.weatherapi.com/v1/current.json?key=" +
        API_KEY +
        "&q=United States";
      const request = await axios.get(url);
      console.log(request.data);
    } catch (err) {
      console.log(err.message, "+", err.code);
    }
  };
  useEffect(() => {
    api_call();
  }, []);

you needed to access the data object from the axios request, you shouldn't have to stringify the response like you stated below

Sign up to request clarification or add additional context in comments.

Comments

0

request and response are objects. Passing a string + object to console.log will cast the object to a string. So if you want to print the content of the object, you should use console.log like this

console.log('response -', response)

Comments

0

This was a bad question. What happened was not that I got no response, but that the response wasn't a string (it was a JSON).

I used JSON.stringify() to turn it into string.

Comments

0

I think that you are getting the response successfully, but the problem is how you are writing it on console.

console.log('response -' + response)

In above console.log, the response object will be convert to a string(since you are trying to concatenate it with a string), so that is the reason you are seeing that [object object] on console.

Instead use:

console.log('response -', response);

This will give the value of response correctly on console.(Including url, data, status etc)

If you just want data, then use:

console.log('response -', response.data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.