Jack_T
Jack_T

Reputation: 125

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} />

Upvotes: 1

Views: 601

Answers (2)

Hrusikesh
Hrusikesh

Reputation: 651

As weatherData is initialized as an empty object so that I'm trying to convert it to string using JSON stringify method and compare it with an empty object now what happens initially CurrentWeather component will not render but when weatherData gets some data from API the condition becomes false and it will render the child component

JSON.stringify(weatherData) !== JSON.stringify({}) 
&& ( <CurrentWeather weather={weatherData} /> )
// this can be rendered like this as well not a preferred way but does the 
// job by comparing two objects

Upvotes: 1

David
David

Reputation: 218837

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.)

Upvotes: 2

Related Questions