skip to Main Content

I have fetched json data from API and am trying to display it. Am able to console log the array but have been unable to display in a div. Map() function does not work on this data.

React / Next.js app

Trying to display json object in div but getting TypeError on map() function.

const getCurrentData = async () => {
    const res = await fetch("http://api.weatherapi.com/v1/current.json?key=84703323c7f94238a98203306233010&q=London&aqi=no")
    return res.json();
};


export default async function Weather() {
    const current = await getCurrentData();
    return (
        <>
            {current.map((current: any, index) => {
                <div key="{index}">
                    <span>{current.location}</span>
                    <span>{current.humidity}</span>
                </div>
            })}
        </>
    );
}

2

Answers


  1. Chosen as BEST ANSWER

    I have refactored but still have an error:

    Error: Objects are not valid as a React child....

    "use client"
    import { useState, useEffect } from "react";
    
    const App = () => {
        const [current, setCurrent] = useState("");
    
        useEffect(() => {
            const url = "http://api.weatherapi.com/v1/current.json?key=84703323c7f94238a98203306233010&q=London&aqi=no";
    
            const fetchData = async () => {
                try {
                    const response = await fetch(url);
                    const json = await response.json();
                    console.log(json.current);
                    setCurrent(json.current);
                } catch (error) {
                    console.log("error", error);
                }
            };
    
            fetchData();
        }, []);
    
        return (
            <>
                <div>{current}</div>
            </>
        );
    };
    
    export default App;
    

  2. React components can not be asynchronous functions. Instead they should be pure and isolate side effects.

    Use useState to fetch data and use useState to then display it inside your application.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search