1

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} />
Jack_T
  • 125
  • 7

2 Answers2

2

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

David
  • 208,112
  • 36
  • 198
  • 279
1

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
Hrusikesh
  • 185
  • 9
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Dec 10 '22 at 09:26