aboutsummaryrefslogtreecommitdiff
path: root/src/routes/authentication/AuthProvider.tsx
blob: a705f074dbfd72ba4cb34502bd14fcd63754585e (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import AsyncStorage from '@react-native-community/async-storage';
import React, {createContext, useEffect, useState} from 'react';
import {
  GET_FB_POSTS_ENDPOINT,
  GET_IG_POSTS_ENDPOINT,
  GET_TWITTER_POSTS_ENDPOINT,
} from '../../constants';
import {
  loadAvatar,
  loadCover,
  loadProfileInfo,
  loadRecentlySearchedUsers,
  loadSocialPosts,
} from '../../services';
import {
  ProfilePreviewType,
  ProfileType,
  SocialAccountType,
  UserType,
} from '../../types';

interface AuthContextProps {
  user: UserType;
  profile: ProfileType;
  login: (userId: string, username: string) => void;
  logout: () => void;
  avatar: string | null;
  cover: string | null;
  socialAccounts: Record<string, SocialAccountType>;
  recentSearches: Array<ProfilePreviewType>;
  newMomentsAvailable: boolean;
  updateMoments: (value: boolean) => void;
}

const NO_USER: UserType = {
  userId: '',
  username: '',
};

const NO_PROFILE: ProfileType = {
  biography: '',
  website: '',
  name: '',
};

// Not necessary, but safer, in case SocialAccountType object is undefined
const NO_SOCIAL_ACCOUNTS: Record<string, SocialAccountType> = {
  Instagram: {},
  Facebook: {},
  Twitter: {},
};

export const AuthContext = createContext<AuthContextProps>({
  user: NO_USER,
  profile: NO_PROFILE,
  login: () => {},
  logout: () => {},
  avatar: null,
  cover: null,
  socialAccounts: NO_SOCIAL_ACCOUNTS,
  recentSearches: [],
  newMomentsAvailable: true,
  updateMoments: () => {},
});

/**
 * Authentication provider for the application.
 */
const AuthProvider: React.FC = ({children}) => {
  const [user, setUser] = useState<UserType>(NO_USER);
  const [profile, setProfile] = useState<ProfileType>(NO_PROFILE);
  const [avatar, setAvatar] = useState<string | null>(null);
  const [cover, setCover] = useState<string | null>(null);
  const [socialAccounts, setSocialAccounts] = useState<
    Record<string, SocialAccountType>
  >(NO_SOCIAL_ACCOUNTS);
  const [recentSearches, setRecentSearches] = useState<
    Array<ProfilePreviewType>
  >([]);
  const [newMomentsAvailable, setNewMomentsAvailable] = useState<boolean>(true);
  const {userId} = user;
  useEffect(() => {
    if (!userId) {
      return;
    }

    const loadData = async () => {
      try {
        const token = await AsyncStorage.getItem('token');
        if (!token) {
          setUser(NO_USER);
          return;
        }
        loadProfileInfo(token, userId, setProfile);
        loadAvatar(token, userId, setAvatar);
        loadCover(token, userId, setCover);
        loadRecentlySearchedUsers(setRecentSearches);
        loadSocialPosts(
          token,
          userId,
          'Instagram',
          GET_IG_POSTS_ENDPOINT,
          socialAccounts,
        ).then((newSocialAccounts) => setSocialAccounts(newSocialAccounts));
        loadSocialPosts(
          token,
          userId,
          'Facebook',
          GET_FB_POSTS_ENDPOINT,
          socialAccounts,
        ).then((newSocialAccounts) => setSocialAccounts(newSocialAccounts));
        loadSocialPosts(
          token,
          userId,
          'Twitter',
          GET_TWITTER_POSTS_ENDPOINT,
          socialAccounts,
        ).then((newSocialAccounts) => setSocialAccounts(newSocialAccounts));
      } catch (err) {
        console.log(err);
      }
    };
    loadData();
  }, [socialAccounts, userId]);

  return (
    <AuthContext.Provider
      value={{
        user,
        profile,
        avatar,
        cover,
        newMomentsAvailable,
        socialAccounts,
        login: (id, username) => {
          setUser({...user, userId: id, username});
        },
        logout: () => {
          try {
            new Promise(() => {
              AsyncStorage.removeItem('token');
            }).then(() => {
              setUser(NO_USER);
            });
          } catch (err) {
            console.log(err);
          }
        },
        recentSearches,
        updateMoments: (value) => {
          setNewMomentsAvailable(value);
        },
      }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;