I'm updating the shared state in context through a callback in the child component, but that does not cause a re-render, which results in the context in the child component having an initial value until the next re-render.
Is there a way to force the update of the child and a re-render once state is updated in the context provider?
My context provider:
const UserLocationContext = React.createContext()
export const useUserLocation = () => {
return useContext(UserLocationContext)
}
export const UserLocationProvider = ({ children }) => {
const [ipUserLocation, setIpUserLocation] = useState(null)
const updateIpUserLocation = (ipUserLocation) => {
setIpUserLocation(ipUserLocation)
console.log(ipUserLocation) //value is updated here immediately after the updateIpUserLocation call
}
return (
<UserLocationContext.Provider value = {{ipUserLocation, updateIpUserLocation}}>
{children}
</UserLocationContext.Provider>
)
}
export default UserLocationProvider
Child:
const LocationHandler = () => {
const {ipUserLocation, updateIpUserLocation} = useUserLocation()
useEffect(() => {
const ip_url = `https://api.freegeoip.app/json/`
const fetchIPLocation = async () => {
const result = await fetch(ip_url);
const json = await result.json();
updateIpUserLocation([json.latitude, json.longitude])
console.log(ipUserLocation) //value here remains null until next re-render
}
fetchIPLocation()
}, []);}