-1

I am using context since props confuse me a lot and when I use it on a Click function both the setState function and fetch function run simultaneously and I get an error since the query is not passed in yet. I tried using setTimeout but

The onClick where it set the query and get fetchFunction

1

it didn't make a difference

enter image description here

context where I store most my state and function

2

also the context but the remaining part

3

vimuth
  • 5,064
  • 33
  • 79
  • 116
Sanket
  • 15
  • 5

1 Answers1

0

This is because updating state is an asynchronous process in react. So setQuery is async here in your case.

That means setQuery and getWeather both are running in parallel.

Solution:

Use useEffect hook to keep watch on query in WeatherProvider

useEffect(() => {
  getWeather(); // this will be called after query is updated
}, [query]);

That's it!

And remove getWeather function call from onClick function, just keep setQuery.

const onClick = () => {
  setQuery(input);
}
Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52
  • As you suggested useEffect did work but now the state changes even when the page is reloaded. And I did change the name of the query to cityName because I thought that browser was taking the query as default blank and loaded the state function Search() { const {setCityName, getWeather, cityName} = useContext(WeatherContext) const[input, setInput] = useState('') const onChange = (e) => { setInput(e.target.value) } const onClick = () => { setCityName(input) } useEffect(() => { getWeather() }, [cityName]) – Sanket Aug 30 '22 at 08:34
  • I don't know how to add code so it became a mess in the comments – Sanket Aug 30 '22 at 08:37
  • On page load, you get control in useEffect because your state gets initialized with empty string "". To overcome that you can make condition in useEffect like `if (cityName) { getWeather(); }` so that it does not called with empty cityName on page load. And please approve the answer if it helped you. – Surjeet Bhadauriya Aug 30 '22 at 11:03