File size: 2,036 Bytes
6c4e56e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import React, { createContext, useContext, useState, useCallback } from "react";
import { authAPI } from "../services/api";
import { useHistory } from "react-router-dom";
import { ROUTES } from "../lib/constants";

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const history = useHistory();

  const handleAuthError = useCallback((error) => {
    setError(error);
    setIsLoading(false);
    setUser(null);
  }, []);

  const login = async (credentials) => {
    try {
      setIsLoading(true);
      const { data } = await authAPI.login(credentials);
      await localStorage.setItem("messenger-token", data.token);
      setUser(data);
      history.push(ROUTES.HOMEPAGE);
    } catch (error) {
      handleAuthError(error);
    } finally {
      setIsLoading(false);
    }
  };

  const register = async (credentials) => {
    try {
      const { data } = await authAPI.register(credentials);
      await localStorage.setItem("messenger-token", data.token);
      setUser(data);
      history.push(ROUTES.ONBOARDING);
    } catch (error) {
      handleAuthError(error);
    }
  };

  const logout = async () => {
    try {
      await authAPI.logout();
      await localStorage.removeItem("messenger-token");
      setUser({});
      history.push(ROUTES.LOGIN);
    } catch (error) {
      handleAuthError(error);
    }
  };

  const clearError = () => setError(null);

  return (
    <AuthContext.Provider
      value={{
        user,
        setUser,
        login,
        register,
        logout,
        error,
        clearError,
        isLoading,
        isAuthenticated: !!user?.id,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};