'Component not re-rendering when context is updated
I have a component that uses the context, but does not re-render when the context is updated.
App.tsx
const AppContext = createContext({
isLoggedIn: false,
hasUserLoggedInBefore: false,
});
const useAppContext = () => useContext(AppContext);
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [hasUserLoggedInBefore, setHasUserLoggedInBefore] = useState(
false
);
useEffect(() => {
// to set up initial state
asyncApiCall
.then((result) => {
if (result["user"]) {
setIsLoggedIn(true);
} else {
setIsLoggedIn(false);
}
if (result["hasUserLoggedInBefore"]) {
setHasUserLoggedInBefore(true);
} else {
setHasUserLoggedInBefore(false);
}
});
// to listen for changes
// this does not seem to re-render <UserControl />
listenToOnAuthChangeEvent((user) => {
setIsLoggedIn(true);
setHasUserLoggedInBefore(true);
});
});
return (
<AppContext.Provider
value={{
isLoggedIn,
hasUserLoggedInBefore,
}}
>
<div className="App">
<Routes>
<Route element={<UserControl />}>
<Route path="/" element={<Functionality />} />
</Route>
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
</Routes>
</div>
</AppContext.Provider>
);
}
And component that uses the context
UserControl.tsx
function UserControl() {
const { isLoggedIn, hasUserLoggedInBefore } = useAppContext();
if (!isLoggedIn) {
return (
<Navigate to={hasUserLoggedInBefore ? "/login" : "/signup"} />
)
}
return (
<Outlet />
)
}
The async API call will fetch the data. If the user is not logged in, display either the sign up or login page based on whether they have ever logged in in the past. If they are logged in, display <Functionality />.
From what I can tell, after the API call succeeds and the set methods are called, the UserControl component does not re-render to display <Functionality />, and the <Signup /> component is displayed again.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
