Skip to content

Instantly share code, notes, and snippets.

@MrMeison
Created September 14, 2022 16:17
Show Gist options
  • Save MrMeison/eade28053260ebc3d878712523118efc to your computer and use it in GitHub Desktop.
Save MrMeison/eade28053260ebc3d878712523118efc to your computer and use it in GitHub Desktop.
// Auth провайдер, обертка для прокидывания информации о пользователе
const AuthProvider = ({ children }) => {
const currentUser = JSON.parse(localStorage.getItem('user'));
const [user, setUser] = useState(currentUser ? { username: currentUser.username } : null);
const logIn = (userData) => {
localStorage.setItem('user', JSON.stringify(userData));
setUser({ username: userData.username });
};
const logOut = () => {
...
};
const getAuthHeader = () => {
...
};
return (
<AuthContext.Provider value={{
logIn, logOut, getAuthHeader, user,
}}
>
{children}
</AuthContext.Provider>
);
};
// на странице чата
const auth = useAuth();
useEffect(() => {
const fetchData = async () => {
try {
const res = await axios.get(routes.dataPath(), { headers: auth.getAuthHeader() });
...
} catch (err) {
if (err.response?.status === 401) {
navigate('/login');
}
}
fetchData();
}, [auth, navigate]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment