I’m building an application using React and Typescript and I want to auth users and keep the authenticated user in the context, but my context is not updating correctly.
Edit: After inspection it seems like the context is being updated correctly, but the UI is not being re-rendered and I dont know why.
AuthProvider.tsx
import { createContext, useState, Dispatch, SetStateAction, useMemo } from "react";
interface AuthContextProps {
auth?:{}, // Refactor this for a authInterface with correct keys
setAuth?: Dispatch<SetStateAction<{} | null>>
}
export const AuthContext = createContext<AuthContextProps>({
auth: null,
setAuth: (prevState: SetStateAction<{} | null>) => prevState
})
export const AuthProvider = ({ children }:any) => {
const [auth, setAuth] = useState<AuthContextProps>(undefined)
const value = useMemo(() => ({ auth, setAuth }), [auth, setAuth])
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}
which is used in App.tsx I think correctly
function App() {
return (
<AuthProvider>
<Router>
<Routes>
<Route path="/" element={<LoginRoute />} />
<Route element={<PrivateRoute />}>
<Route path="home" element={<HomeRoute />} />
</Route>
</Routes>
</Router>
</AuthProvider>
)
}
export default App
The PrivateRoute.tsx is just a wrapper that should handle rendering correct routes (where is auth required)
export const PrivateRoute = () => {
const fallbackRoute = "/";
const {auth} = useContext(AuthContext);
return auth ? (
<Navigate to="/home" />
) : (
<Navigate to={fallbackRoute} />
);
};
and when login form is submitted, I (try to) update the state like this (the body is a dummy response from auth server)
setAuth({
status: 200,
token: "someTokenDoesntMatter",
user: {
id: 1,
email: "[email protected]",
f_name: "Jan",
l_name: "Novak",
username: "jan.novak"
}
})
Which I think passes correctly, because when I log auth object into the console, it prints the correct data.
console.log() of the auth object
But the endpoint route keeps unchanged, even though I thought that in PrivateRoute.tsx I said that if the auth object exists (is not null or undefined) the children components (routes) will be rendered since the component, but that doesnt happen.
Any help is very much appreciated and pardon me if I missed something banal and this is a stupid question.