Interview question
How do you handle authentication state? Authentication state कैसे handle करें?
Answer
// Authentication context
const AuthContext = createContext();
function AuthProvider({ children }) {
const [auth, setAuth] = useState(null);
const login = async (email, password) => {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});
const data = await response.json();
setAuth(data);
localStorage.setItem('token', data.token);
};
const logout = () => {
setAuth(null);
localStorage.removeItem('token');
};
return (
<AuthContext.Provider value={{ auth, login, logout }}>
{children}
</AuthContext.Provider>
);
}Context से auth state manage कर सकते हैं।Was this answer clear?