Search code examples
reactjstypescriptreact-reduxreact-context

Context api useContext is not updating, always returning null


I've go my context,

export const LocationContext = createContext(null);
export const LocationProvider = LocationContext.Provider;
export const useLocationContext = () => useContext(LocationContext);

Provider,

export const Search = () => {
    const [ location, setLocation ] = useState(null)
    
    const handleLocateMe = () => {
        navigator.geolocation.getCurrentPosition((position) => {
            setLocation( { lat: position.coords.latitude, lon: position.coords.longitude} )
        });
    }

    return(
        <LocationProvider value={{location}}>
            <MapUISearch />
            <MapUIBtn _iconName={SmileOutlined} _type="primary" _className={styles.locateMe} _fn={()=> {handleLocateMe()}} />
        </LocationProvider>
    )
}

useContext,

const { location } = useLocationContext();

Issue is it always throws Cannot destructure property location of 'undefined' or 'null'.

and useLocationContext is never gets updated and returns the default value of null

FYI: I've got same implementation for another context, which works as expected

Thanks in advance


Solution

  • I totally forgot that provider has to be on the higher (parent) component. My provider sat on the child component. Just had to change the provider to parent component and useContext to child components.