MagnusEffect
MagnusEffect

Reputation: 3925

Want to display a default data from API as soon as page opens before any input by user?

Intro

I am fetching data from openweatherAPI and it is being shown in the console and page also.

Problem

But I am not able to display the default data on the front end as soon as the page opens for the first time (before inputting any value and click)? Although after inputting the value and click, I am able to display the data for that city.

What I want ?

I am able to display data.day and data.week but what I want that as soon as the page opens it should display default data (of any city like Delhi). That means I had to call the API again through useEffect. But it is not working.

Code

import Head from "next/head";
import {useEffect} from 'react';
import Image from "next/image";
import { useState } from "react";
import { useRouter } from "next/router";
import Today_highlight from "./components/Today_highlight";
import Weather_Today from "./components/Weather_Today";
import Weather_week from "./components/Weather_week";
import searchimageurl from "../public/search.gif";



export default function Home() {
  //console.log("res1 = ", results1);
  const router = useRouter();
  const [city, setCity] = useState("");
  const [data, setData] = useState({
    day:{},week:{}
  });

  useEffect(() => {
  
    async function apiCallFunction() {
      const url = `https://api.openweathermap.org/data/2.5/weather?q=Delhi&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
      const res = await fetch(url);
      const data1 = await res.json();
      console.log(data1);
  
      //api-2
      const url1 = `http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
      const res1 = await fetch(url1);
      const data2 = await res1.json();
      console.log(data2);
      //return {data,data1}
      setData({ day: data1, week: data2 });
    }
  }, [])
  

  const handleChange = (e) => {
    setCity(e.target.value);
    //console.log(city)
  };

  const handleSubmit = async (e) => {
    //console.log("%c ClickSubmit","font-size:12px; color:green; padding:10px;")
    console.log("city = ", city);
    //router.push(`/?term=${city}`);

    const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
    const res = await fetch(url);
    const data1 = await res.json();
    console.log(data1);

    //api-2
    const url1 = `http://api.openweathermap.org/data/2.5/forecast/daily?q=${city}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
    const res1 = await fetch(url1);
    const data2 = await res1.json();
    console.log(data2);
    //return {data,data1}
    setData({ day: data1, week: data2 });
  };

  const kelvinToCelcius = (temp) => {
    return (temp - 273.15).toPrecision(3) + "°";
  };

  return (
    <>
      <Head>
        <title>Weather-Lytics</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      {/* input */}
      <div className="p-3 xl:p-10 flex flex-row justify-center items-center space-x-2 xl:space-x-5 bg-blue-900">
        <div className="bg-lime-300 border-2 border-stone-700 rounded-full ">
          <input
            className="w-full rounded-full p-2 xl:p-4 text-base xl:text-3xl text-blue-800 font-bold active:rounded-full "
            value={city}
            placeholder="Enter city"
            onChange={handleChange}
          />
        </div>
        <div>
          <button className="p-1 m-auto p-auto" onClick={() => handleSubmit()}>
            <div className="w-14 h-14 xl:w-16 xl:h-16 p-2 rounded-full bg-pink-400 border-2 hover:bg-pink-600 border-white">
              <Image
                src={searchimageurl}
                layout="responsive"
                alt="Search_icon"
                className=" rounded-full p-3 bg-blue-900 "
              />
            </div>
          </button>
        </div>
      </div>

      <div className="min-h-full bg-red-400 flex flex-col lg:flex-row">
        <div className="bg-blue-300 w-full lg:w-1/4 lg:h-full">
          <Weather_Today results={data.day} kelvinToCelcius={kelvinToCelcius} />
        </div>
        <div className="bg-green-500 w-full lg:h-full ">
          <div className="min-h-full flex flex-col">
            <div className="bg-yellow-400 w-full">
              <Today_highlight
                results={data.day}
                kelvinToCelcius={kelvinToCelcius}
              />
            </div>
            <div className="bg-orange-600 w-full">
              <Weather_week
                results1={data.week}
                kelvinToCelcius={kelvinToCelcius}
              />
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// export async function getServerSideProps({ query }) {
//   // if there is no query
//   if (!query.term) query.term = "Bhopal";

//   //api-1
//   const url = `https://api.openweathermap.org/data/2.5/weather?q=${query.term}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
//   const res = await fetch(url);
//   const data = await res.json();
//   //console.log(data);

//   //api-2
//   const url1 = `http://api.openweathermap.org/data/2.5/forecast/daily?q=${query.term}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
//   const res1 = await fetch(url1);
//   const data1 = await res1.json();
//   //console.log(data1);

//   return {
//     props: {
//       results: data,
//       results1: data1,
//     },
//   };
// }


I don't want to give a default value Delhi to the

const [city,setCity] = useState('Delhi')

because this value will also be there displayed in the input all the time as soon as no one input the text?

How to do so?

Upvotes: 1

Views: 192

Answers (1)

jcobo1
jcobo1

Reputation: 1180

Where you define the url you could conditionally set the city value try this:

const url = `https://api.openweathermap.org/data/2.5/weather?q=${city || 'Delhi'}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;

const url1 = `http://api.openweathermap.org/data/2.5/forecast/daily?q=${city || 'Delhi'}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;

This way if city has a value it will take the city value if not it will take Delhi.

Upvotes: 1

Related Questions