0

I'm trying to create a customised homepage for my browser. I have implemented an API to show the weather, but only works when I press enter. I want to display the data automatically when loads the page, without pressing enter, showing the Bristol weather automatically and when I type another location the api will be able to request and render. I tried a lot of ways like (removing the hook, changing the initial state of the hook but nothing seems to work)This is my code:

    const [query, setQuery] = useState('Bristol');
    const [weather, setWeather] = useState({});

const search = async () => {
    fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
    .then(res => res.json())
    .then(result => {
        setWeather(result);
        setQuery('')
        console.log(result)
    });
}
    return(
        <div className="app">
            <main>
                <div className="search-box">
                    <input
                        type="text"
                        className="search-bar"
                        placeholder="Search..."
                        onChange={e => setQuery(e.target.value)}
                        value={query}
                        onKeyPress={search}
                    />
                </div>
                {(typeof weather.main != "undefined") ? (
                    <div>
                    <div className="location-box">
                        <div className="location">{weather.name}</div>
                        <div className="date">{dateBuilder(new Date())}</div>
                    </div>
                        <div className="weather-box">
                            <div className="temp">
                                {Math.round(weather.main.temp)}
                            </div>
                            <div className="weather">
                                {weather.weather[0].main}
                            </div>
                        </div>
                    </div>
                ) : ('')}
            </main>
        </div>
    )
} 

I'm new to ReactJS and it's a bit confusing, because here I use the same file to code and to render, I did this before but I was using plain JavaScript with express, etc.. and I rendered into an HTML.

3

2 Answers 2

1
useEffect( () => search(), [])  
Sign up to request clarification or add additional context in comments.

2 Comments

I guess the approach in my answer is more idiomatic as it will automatically re-execute the search when the query changes. Also it eliminates the imperative onKeyPress={search} event handler
you can use useEffect and pass the search query to the dependecies table, so every time the variable changes it will make a re_render with the new result.
1

Try wrapping the fetch call in useEffect:

  useEffect(() => {
    fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
      .then((res) => res.json())
      .then((result) => {
        setWeather(result);
        console.log(result);
      });
  }, [query]);

The second argument is a so called dependency array. Whenever its contents change the effect will be rerun, see https://reactjs.org/docs/hooks-effect.html.

Also remove onKeyPress={search} as it is redundant with onChange={e => setQuery(e.target.value)}

Further resources:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.