import React, { createContext, useContext, useEffect, useReducer } from "react";
import { User } from "../libs/types";
import Cookies from "js-cookie";
import { useMoralis } from "react-moralis";
interface IState {
user: User|null;
loading?: boolean;
}
interface IAction {
type: "REMOVE_USER" | "SET_USER" | "STOP_LOADING"|"ETH_Address";
payload?: User;
}
interface useTweetsProps {
children?: React.ReactNode;
}
// create two context; one for the state and one for the dispatch
const StateContext = createContext<IState>(undefined!); //create context default value only useful for testing
//https://stackoverflow.com/questions/49949099/react-createcontext-point-of-defaultvalue
const DispatchContext = createContext<React.Dispatch<IAction>>(null!);
//
//const reducer = (state: any, action: { type: any; payload: any; }) => {
const Jackson= (state: IState, action: IAction) => {
switch (action.type) {
case 'SET_USER':
return { ...state, username: action.payload };
case 'ETH_Address':
return { ...state, ethAddress: action.payload };
default:
throw new Error(`Unknown action type: ${action.type}`);
}
};
export function AuthProvider({children}: useTweetsProps): JSX.Element {
//export const AuthProvider = ({children}:useTweetsProps) => {
const { Moralis, account , isInitializing, isInitialized,} = useMoralis();
const [state, dispatch] = useReducer<React.Reducer<IState, IAction>>(Jackson, {
user: null,
loading: true, // might be needed later :(
});
useEffect(() => {
async function loadUser() {
try {
// set initially from cookie
/* dispatch({
type: "SET_USER",
payload: Cookies.get("user") ? JSON.parse(Cookies.get("user")) : null,
}); */
const res = await Moralis.Cloud.run("getUsers");
dispatch({
type: "SET_USER",
payload: res.data.username,
});
Cookies.set("username", res.data);
console.log("res.data"+res.data);
dispatch({
type: "ETH_Address",
payload: res.data.ethAddress,
});
Cookies.set("ethAddress", res.data.ethAddress);
} catch (error) {
console.log("error"+error);
/** Cookies.remove("user");
dispatch({
type: "REMOVE_USER",
}); */
} /**finally {
dispatch({
type: "STOP_LOADING",
});
} */
}
isInitialized && loadUser();
}, [Moralis.Cloud,isInitialized]);
return (
<DispatchContext.Provider value={dispatch}>
<StateContext.Provider value={state}>{children}</StateContext.Provider>
</DispatchContext.Provider>
);
};
export const useAuthState = () => useContext(StateContext);
export const useAuthDispatch = () => useContext(DispatchContext);
export interface User {
id: string;
ethAddress: string;
username: string;
pfp: string;
banner: string;
bio: string;
likes: string;
following: string;
followers: string;
// virtual fields
noOfFollowers: number;
noOfFollowing: number;
tweets: string;
noOPosts: number;
}