Home > front end >  How to get API data before it's passed to props React
How to get API data before it's passed to props React

Time:12-10

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

CodePudding user response:

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

CodePudding user response:

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
  • Related