-
-
Save MrMeison/eade28053260ebc3d878712523118efc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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