I've got a context shared amongst a group of profile pages. The context is responsible for loading and setting the user's profile from a database, like so:
const Profile = props => {
const { userProfile } = useContext(ProfileContext);
return userProfile && (
<div className="profile-container">
...stuff
</div>
);
};
export default Profile;
...routes:
<BrowserRouter>
<Header />
<main className="main-container">
<Switch>
...other routes
<ProfileContextProvider>
<Route path="/profile/:id" exact component={Profile} />
<Route path="/settings" exact component={Settings} />
</ProfileContextProvider>
</Switch>
</main>
<Footer />
</BrowserRouter>
The context itself is very simple:
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
export const ProfileContext = React.createContext({
userProfile: {},
setUserProfile: () => {}
});
ProfileContext.displayName = "ProfileContext";
const ProfileContextProvider = props => {
const { id } = useParams(); //always undefined!
const [userProfile, setUserProfile] = useState(null);
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
...api call to load data
};
return (
<ProfileContext.Provider value={{
userProfile,
setUserProfile
}}>
{props.children}
</ProfileContext.Provider>
);
};
export default ProfileContextProvider;
However, that use of useParams() in there doesn't work. The "id" is always undefined. If I move this useParams() usage to the Profile component itself, it works fine. This does me no good, because I need to make a decision about the route, when loading data in the context, before I load all of Profile. I need it to work in the context!
Is this possible? Am I doing something wrong?
Context is itself different management and query param should props from the page to context set variable then it works