Is there a way to pass this state from component to the fetch?

Joined
Sep 12, 2022
Messages
39
Reaction score
0
Without using any state management library, I want to pass the location state from InputsAndBtn component into the fetch in the WeatherApi() so API searches can be done with the input location. Note that they are in different files but in the same folder, how do I do this as I am stuck and I do not want to move them into one file?

JSX:
import { API_KEY, BASE_URL } from "./keys";
import { useEffect, useState } from "react";

const WeatherApi = ({location}) => {
  const [apiData, setApiData] = useState(null);

  useEffect(() => {
      fetch(`${BASE_URL}weather?q=${location}&appid=${API_KEY}`)
        .then((res) => res.json())
        .then((data) => {
          setApiData(data);
          console.log(data);
        })
        .catch((error) => console.log(error));
  }, []);

  return { apiData };
};

export default WeatherApi;


JSX:
import { useState } from "react"
import './App.css';
import  WeatherApi  from "./api";


const InputsAndBtn = () => {
    const [location, setLocation] = useState("")
    const {apiData} = WeatherApi({ location })
    const [clouds, setClouds] = useState(null)
    const [description, setDescription] = useState(null)

    function handleChange(event) {
        setLocation(event.target.value)
    }
    function handleClouds() {
        setClouds(apiData.clouds.all)
    }
    function handleDescription() {
        setDescription(apiData.weather[0]["description"])
    }
    function handleBtn(event) {
        event.preventDefault()
            if(location === apiData.name) {
                handleClouds()
                handleDescription()
            }
    }
    return (
        <form className="form">
            <div style={{display: "flex"}}>
                <section style={{marginRight: "auto"}}>
                    <input
                    onChange={handleChange}
                    type="text"
                    placeholder="enter a city"
                    value={location}
                    >
                    </input>
                    <button onClick={handleBtn}>Start</button>
                </section>
                {clouds && <section style={{backgroundColor: "red", width: "30vw", height: "100vh"}}>
                    <h1>{clouds}</h1>
                    <h2>{description}</h2>
                </section>}
            </div>
        </form>
    )
}

export default InputsAndBtn
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
One way to pass the location state from InputsAndBtn component to the WeatherApi component is by creating a prop for location in the WeatherApi component and passing the location state as a prop while calling the WeatherApi component in the InputsAndBtn component.

Here is how you can modify your code to achieve this:

WeatherApi.js:
JSX:
import { API_KEY, BASE_URL } from "./keys";
import { useEffect, useState } from "react";

const WeatherApi = ({ location }) => {
  const [apiData, setApiData] = useState(null);

  useEffect(() => {
    fetch(`${BASE_URL}weather?q=${location}&appid=${API_KEY}`)
      .then((res) => res.json())
      .then((data) => {
        setApiData(data);
        console.log(data);
      })
      .catch((error) => console.log(error));
  }, [location]);

  return { apiData };
};

export default WeatherApi;
InputsAndBtn.js:

JSX:
import { useState } from "react"
import './App.css';
import  WeatherApi  from "./api";


const InputsAndBtn = () => {
    const [location, setLocation] = useState("")
    const {apiData} = WeatherApi({ location })
    const [clouds, setClouds] = useState(null)
    const [description, setDescription] = useState(null)

    function handleChange(event) {
        setLocation(event.target.value)
    }
    function handleClouds() {
        setClouds(apiData.clouds.all)
    }
    function handleDescription() {
        setDescription(apiData.weather[0]["description"])
    }
    function handleBtn(event) {
        event.preventDefault()
            if(location === apiData.name) {
                handleClouds()
                handleDescription()
            }
    }
    return (
        <form className="form">
            <div style={{display: "flex"}}>
                <section style={{marginRight: "auto"}}>
                    <input
                    onChange={handleChange}
                    type="text"
                    placeholder="enter a city"
                    value={location}
                    >
                    </input>
                    <button onClick={handleBtn}>Start</button>
                </section>
                {clouds && <section style={{backgroundColor: "red", width: "30vw", height: "100vh"}}>
                    <h1>{clouds}</h1>
                    <h2>{description}</h2>
                </section>}
            </div>
        </form>
    )
}

export default InputsAndBtn
In the WeatherApi component, we have added a prop called location and passed it to the fetch URL in useEffect. In the InputsAndBtn component, we have passed the location state as a prop to the WeatherApi component while calling it. This should allow you to pass the location state from the InputsAndBtn component to the WeatherApi component.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,703
Messages
2,569,328
Members
44,612
Latest member
Billysak

Latest Threads

Top