Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
    }, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading