index.js 2.11 KB
import { createContext, useContext, useState } from "react";
import * as api from "../lib/api";
import { toast } from "react-toastify";
export const AppContext = createContext();
export const useAppContext = () => useContext(AppContext);

export function ContextProvider({ children }) {
  const [userseats, setUserSeats] = useState([]);
  const [seats, setSeats] = useState([]);
  const [isLoading, setisLoading] = useState(false);
  const LoginOrRegister = async ({ mobile }) => {
    try {
      const user = await api.GetUserByMobile({ mobile });
      if (!user.length) {
        //register
        const response = await api.Register({ mobile });
        return await response;
      } else {
        //login
        return await user[0];
      }
    } catch (err) {
      toast.error(err.message);
    }
  };
  const AddOrUpdateSeats = async ({ id, seats }) => {
    try {
      const isSeats = userseats.filter((e) => e.id == id);
      //check the id
      if (!isSeats.length) {
        //add seats
        const response = await api.AddSeats({ seats });
        setUserSeats([...userseats, response]);
      } else {
        //update seats
        const response = await api.UpdateSeats({ id, seats });
        const result = userseats.map((e) => (e[id] == id ? response : e));
        setUserSeats(result);
      }
    } catch (err) {
      toast.error(err.message);
    }
  };
  const GetAllSeats = async () => {
    setisLoading(false);
    try {
      //to clear the data for glitch
      setUserSeats([]);
      const response = await api.GetAllSeats();
      setUserSeats(response);
      setisLoading(true);
    } catch (err) {
      toast.error(err.message);
    }
  };

  const GetSeats = async () => {
    setisLoading(false);
    try {
      setSeats([]);
      const response = await api.GetSeats();
      setSeats(response);
      setisLoading(true);
    } catch (err) {
      toast.error(err.message);
    }
  };

  const value = {
    userseats,
    isLoading,
    seats,
    LoginOrRegister,
    AddOrUpdateSeats,
    GetAllSeats,
    GetSeats,
  };
  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}