'wrap userContext around specific routes
I have a userContext like this.
const UserContext = React.createContext();
export function useUserContext() {
return useContext(UserContext);
}
export function UserProvider({ children }) {
const [user, setUser] = useState();
useEffect(() => {
const fetchData = async () => {
const { data } = await userService.UserDetails();
setUser(data);
};
fetchData();
}, []);
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
}
And my app.js with different routes looks like this
<UserProvider>
<ToastContainer />
<Router>
<Switch>
<Route path="/signup" component={Signup} />
<Route path="/login" component={Login} />
<ProtectedRoute path="/configuration" component={Configuration} />
<ProtectedRoute path="/product" component={Product} />
</Switch>
</Router>
</UserProvider>
But I want to wrap userContext around specific routes, in my case only around ProtectedRoutes otherwise an unnecessary api call is done to identify the user even on Login and Signup pages.
What is the proper way to fix this.
Tried one below but it's resulting in page flickering (like loop). What's the way to fix it?
<ToastContainer />
<Router>
<Switch>
<Route path="/signup" component={Signup} />
<Route path="/login" component={Login} />
<UserProvider>
<ProtectedRoute path="/configuration" component={Configuration} />
<ProtectedRoute path="/product" component={Product} />
</UserProvider>
</Switch>
</Router>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
