pastasauce
pastasauce

Reputation: 651

Getting no response calling API using axios in React

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.

Upvotes: 0

Views: 1268

Answers (4)

Siddharth Agrawal
Siddharth Agrawal

Reputation: 116

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)

Upvotes: 0

Yuuko
Yuuko

Reputation: 16

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)

Upvotes: 0

Rob Terrell
Rob Terrell

Reputation: 2562

   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

Upvotes: 1

pastasauce
pastasauce

Reputation: 651

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.

Upvotes: 0

Related Questions