menuItemsAction.js 1.55 KB
import axios from "axios";
import qs from "qs";
import { FETCH_MENU_ITEMS_REQUEST, FETCH_MENU_ITEMS_SUCCESS, FETCH_MENU_ITEMS_FAIL, CLEAR_ERRORS } from "../constants/menuItemsConstants";

export const getMenuItems =
  ({ menu = "Main", published = true }) =>
  async dispatch => {
    const fmir = `${FETCH_MENU_ITEMS_REQUEST}_${menu.toUpperCase()}`;
    const fmis = `${FETCH_MENU_ITEMS_SUCCESS}_${menu.toUpperCase()}`;
    const fmif = `${FETCH_MENU_ITEMS_FAIL}_${menu.toUpperCase()}`;
    const ce = `${CLEAR_ERRORS}_${menu.toUpperCase()}`;

    try {
      dispatch({
        type: fmir
      });

      const itemsPerPage = 100;
      const query = {
        filters: {
          menu: {
            name: {
              $eq: menu
            }
          }
        },
        populate: ["parent"],
        pagination: {
          pageSize: itemsPerPage,
          page: 1
        },
        sort: ['serialNumber:asc'],
        // fields: ['title'],
        // publicationState: 'live',
        // locale: ['en'],
        publicationState: published ? "live" : "preview"
      };

      const queryString = qs.stringify(query, {
        encodeValuesOnly: true
      });

      const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/menu-items?${queryString}`);

      dispatch({
        type: fmis,
        payload: response.data
      });
    } catch (error) {
      console.log("Error while fetching menu items: ");
      console.log(error.response.data);

      dispatch({
        type: fmif,
        payload: error.response.data
      });
    }
  };