javascriptreactjsapiaxios

Why I can't read data from API (React app)


I am learning React and I ran into a problem that I can't solve by myself.

I am trying to get data from API but instead, I get an undefined array.

I created axios.js

import axios from "axios";

const instance = axios.create({
    baseURL: "http://api.weatherapi.com/v1/",
});

export default instance;

Requests.js

const API_KEY = '7be85e2711194910b29123355231904';

export const fetchDataByCity = (city) => {
    return `current.json?key=${API_KEY}&q=${city}&aqi=no`;
}

Page.js

import axios from "../../axios"
import { fetchDataByCity } from "../../Requests";
import { useEffect, useState } from "react";
const Page = props => {
    const [data, setData] = useState([]);
    useEffect(() => {
        async function fetchData() {
            let request = [];
            request = await axios.get(fetchDataByCity("London"));

            setData(request.data.results);
            return request;
        }

        fetchData();
    }, []);

    console.log(data);
    return (
        <div >
            hey
        </div>
    );
}

export default Page;

When I try to display data in the console I get undefined


Solution

  • It is undefined because you are trying to access results key from the response and there is no key return from the response. Response is an object and you are expecting the array from the response.

    useEffect(() => {
            async function fetchData() {
                ....
                <!-- no key `results` exists in the response -->
                setData(request.data.results); 
                ....
            }
    
            fetchData();
        }, []);
    

    Here is the response please check.

    Work around can be like you initialize data state in object and set after response like

    const [data, setData] = useState({}); // object
    
    useEffect(() => {
            async function fetchData() {
                ....
                <!-- remove `results` key  -->
                setData(request.data); 
                ....
            }
    
            fetchData();
        }, []);