I have a context.js as follows and so far the data is hardcoded (latitude and longitude) as well as initial weather values saved as objects in the same format I will receive from the server. I for now have an input box, this will be changed to Google places eventually but I just wanted the functionality working for now.
How can i get the input from the form back to the context to run the fetch request again on the form submit?
The server and the the axios request both work perfect.
My current context.js which is provided in index.js wrapping everything
const AppProivider = ({ children }) => {
const [loading, setLoading] = useState(false);
const [latitude, setLatitude] = useState(54.978252);
const [longitude, setLongitude] = useState(-1.61778);
const [current, setCurrent] = useState(currentx);
const [hourly, setHourly] = useState(hourlyx);
const [future, setFuture] = useState(futurex);
const fetchWeather = useCallback(async () => {
setLoading(true);
try {
const response = await axios.get("http://localhost:8000/weather", {
params: { latitude, longitude },
});
const { current, hourly, future } = await response.data;
if (current && hourly && future) {
setCurrent(current);
setHourly(hourly);
setFuture(future);
} else {
setCurrent(currentx);
setFuture(hourlyx);
setHourly(futurex);
}
setLoading(false);
} catch (error) {
setLoading(false);
console.log(error);
return "There was a problem fetching the weather information, please try again";
}
}, [latitude, longitude]);
useEffect(() => {
fetchWeather();
}, [latitude, longitude, fetchWeather]);
return (
<AppContext.Provider
value={{
loading,
current,
future,
hourly,
setLongitude,
setLatitude,
}}
>
{children}
</AppContext.Provider>
);
};
export const useGlobalContext = () => {
return useContext(AppContext);
};
export { AppContext, AppProivider };
My Current, very basic, App.js to gather the information
import { useGlobalContext } from "../../context";
const App = () => {
const { current, hourly, future, setLatitude } = useGlobalContext();
const [lat, setLat] = useState(1);
const handleChange = (e) => {
e.preventDefault();
setLatitude(lat);
console.log(current);
};
return (
<div>
<form onSubmit={handleChange}>
<input type="number" onChange={(e) => setLat(e.target.value)}></input>
<input type="submit"></input>
</form>
</div>
);
};
export default App;