Using componentDidMount without components? React

Hello everyone. I am build an app that gets the weather info with an API and displays it. Everything is going ok except when the App first loads, because there is no city for the api to search everything returns undefined.
So I thought of using componentDidMount() except this is not a component.
So is there a way to set the search field on page load? Please lend me your expertise.
Thank you in advance.
Full code:

You have multiple ways of doing so:

you can use useEffect hook the same way you are thinking of using componentDidMount

you can add a default value so it won’t break
you can conditionally render the display element to render only if city is defined.

It all depends on your design choices and functionality/tradeoff :slight_smile:
Hope this helps.

1 Like

Hi, thanks for your response! So I tried the react hook,

 useEffect(() => {
    query.current = 'Spokane'

The code is not throwing any errors, however when I load the page I still get that the property is undefined

You initialise your weather object as empty

const [weather, setWeather] = useState({});

Then you are planning to populate it only after a fetch request. Correct?

So how do you want to handle the rendering of location

 <div className="location">
              {}, {}

Which expects a value, but none is provided unless a successful fetch happens?
This is the real question :slight_smile:

You will face the same issue in the weather box div as well.
What should it do if weather is an empty object, as you declared?

        <div className="weather-box">
          <div className="temp">{Math.round(weather.main.temp)}°c</div>

          <div className="weather">{[0].main}</div>
1 Like

So I should set all of them up to where if the value is null, it should return a placeholder. Right?

Thanks for your help. I got the solution.
In case others have this problem

{(typeof weather.main != "undefined") ? ( wrap everything with this ) : ('')}

Glad I could help :slight_smile:

Happy coding :sparkle: