import React, {useEffect} from 'react'; import {createContext, useState} from 'react'; import AsyncStorage from '@react-native-community/async-storage'; import {UserType, ProfileType, InstagramPostType} from '../../types'; import { loadProfileInfo, loadAvatar, loadCover, loadInstaPosts, } from '../../services'; interface ProfileContextProps { user: UserType; profile: ProfileType; loadProfile: (userId: string, username: string) => void; avatar: string | null; cover: string | null; instaPosts: Array; newMomentsAvailable: boolean; updateMoments: (value: boolean) => void; } const NO_USER: UserType = { userId: '', username: '', }; const NO_PROFILE: ProfileType = { biography: '', website: '', name: '', }; export const ProfileContext = createContext({ user: NO_USER, profile: NO_PROFILE, loadProfile: () => {}, avatar: null, cover: null, instaPosts: [], newMomentsAvailable: true, updateMoments: () => {}, }); /** * This is the context provider for user profiles that the logged in user wants to see */ const ProfileProvider: React.FC = ({children}) => { const [user, setUser] = useState(NO_USER); const [profile, setProfile] = useState(NO_PROFILE); const [avatar, setAvatar] = useState(null); const [cover, setCover] = useState(null); const [instaPosts, setInstaPosts] = useState>([]); const [newMomentsAvailable, setNewMomentsAvailable] = useState(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); loadInstaPosts(token, userId, setInstaPosts); } catch (err) { console.log(err); } }; loadData(); }, [userId]); return ( { setUser({...user, userId: id, username}); }, updateMoments: (value) => { setNewMomentsAvailable(value); }, }}> {children} ); }; export default ProfileProvider;