Search code examples
reactjsasync-awaitfetch-apireact-props

How should I use a variable of a function as a prop in React JS


import React, { useState } from 'react'
import Display from './components/Display';
const App = () => {
    const [input,setInput] = useState("");
    
    const getData = async () => {
    const myAPI = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${input}&units=metric&appid=60dfee3eb8199cac3e55af5339fd0761`);
    const response = await myAPI.json();
    console.log(response);                  //want to use response as a prop in Display component
   }

   return(
    <div className="container">
        <h1>Weather Report</h1>
        <Display title={"City Name :"} />         //here
        <Display title={"Temperature :"} />       //here
        <Display title={"Description :"} />       //here
        <input type={input} onChange={e => setInput(e.target.value)} className="input"/>
        <button className="btn-style" onClick={getData}>Fetch</button>
    </div>
   );
}

export default App;

Solution

  • I don't know if I understand you correctly but if I'm right you want to access data returned from your function that is fetching from API, if so you can try this way

    import React, { useState, useEffect } from 'react' 
    import Display from './components/Display';
    import axios from 'axios';
    
    const App = () => {
    const [input,setInput] = useState(""); 
    
    const [state, setState] = useState({loading: true, fetchedData: null});
    
    useEffect(() => {
            getData();
    }, [setState]);
    
    async function getData() {
        setState({ loading: true });
        const apiUrl = 'http://api.openweathermap.org/data/2.5/weather?q=${input}&units=metric&appid=60dfee3eb8199cac3e55af5339fd0761';
        await axios.get(apiUrl).then((repos) => {
            const rData = repos.data;
            setState({ loading: false, fetchedData: rData });
        });
    }
    
    return(
        state.loading ? <CircularProgress /> : ( 
            <List className={classes.root}>
            { state.fetchedData.map((row) => ( 
                <div className="container">
                    <h1>Weather Report</h1>
                    <Display title={"City Name :" + row.cityName } />         //here
                    <Display title={"Temperature :" + row.temperature} />       //here
                    <Display title={"Description :" + row.description} />       //here
                     
                </div>
            )) }
            </List>
        )
    );
    

    }