%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /var/www/html/src/Components/store/context/
Upload File :
Create Path :
Current File : /var/www/html/src/Components/store/context/GlobalContext.js

import { createContext, useReducer, useEffect, useContext } from "react";
import useSWR from "swr";
import { GET_CONTACT, GET_FOOTER, GET_MENU, IS_COLOR } from "../Action";
import reducer from "../reducers/GlobalReducers";

const fetcher = (url) => fetch(url).then((r) => r.json());

const initialState = {
  contact: [],
  menu: [],
  footer: [],
  isColor: "original",
};
const GlobalContext = createContext();

export const GlobalProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  // REQUEST FOR CONTACT
  const { data, error } = useSWR(
    `https://api.atvbuggy-dubrovnik.com/wp-json/api/v1/global`,
    fetcher
  );
  const getContact = () => {
    return dispatch({
      type: GET_CONTACT,
      payload: data.contact,
    });
  };
  const getFooter = () => {
    return dispatch({
      type: GET_FOOTER,
      payload: {
        footer: data.menu.footer,
        socials: data.socials,
        legal: data.legal,
      },
    });
  };
  const getHeader = () => {
    return dispatch({
      type: GET_MENU,
      payload: { header: data.header, menu: data.menu.header },
    });
  };

  const setIsColor = (color) => {
    return dispatch({
      type: IS_COLOR,
      payload: color,
    });
  };

  useEffect(() => {
    if (error) return "An error has occurred.";
    if (!data) return "Loading...";

    getContact();
    getFooter();
    getHeader();
  }, [data]);

  return (
    <GlobalContext.Provider
      value={{
        ...state,
        setIsColor,
      }}
    >
      {children}
    </GlobalContext.Provider>
  );
};

export const useGlobalContext = () => {
  return useContext(GlobalContext);
};

Zerion Mini Shell 1.0