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

How to get API data before it's passed to props React

in my parent component have an API call using fetch which gathers data that then passes to a child component to be displayed. The issue I am having is that it is rendering before the data is gathered and passed through props.

// PARENT COMPONENT
        const [weatherData, setWeatherData] = useState({})
        useEffect(function() {
            const apiKey = ""
            const url =           `https://api.openweathermap.org/data/2.5/weather? 
    q=manchester&units=metric&appid=${apiKey}`
            fetch(url)
            .then(res => res.json())
            .then(data => setWeatherData(data))
        }, [])
// Passing the data through props to child component
    <CurrentWeather weather={weatherData} />

>Solution :

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

You can conditionally render the component based on the current state. For example, if the initial value of weatherData is undefined:

const [weatherData, setWeatherData] = useState();

Then you can conditionally render like this:

{ weatherData ? <CurrentWeather weather={weatherData} /> : null }

or:

{ weatherData && <CurrentWeather weather={weatherData} /> }

Or if you keep the empty object ({}) then your condition can instead test for an empty object. Either way, you "wait" by just not rendering the element(s) until the data is available. (You can further improve the UX by having a temporary "loading" indicator while the data loads, etc.)

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