categoriesAction.js 1.64 KB
import axios from "axios";
import qs from "qs";
import {
  GET_CATEGORIES_FAIL,
  GET_CATEGORIES_REQUEST,
  GET_CATEGORIES_SUCCESS,
  GET_SUB_CATEGORIES_FAIL,
  GET_SUB_CATEGORIES_REQUEST,
  GET_SUB_CATEGORIES_SUCCESS
} from "../constants/categoryConstants";

export const getAllCategories = () => async dispatch => {
  try {
    dispatch({
      type: GET_CATEGORIES_REQUEST
    });
    const config = {
      headers: {
        "Content-Type": "application/json"
      }
    };

    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/categories`, config);

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

    return response.data;
  } catch (error) {
    dispatch({
      type: GET_CATEGORIES_FAIL,
      payload: error.response.data
    });
  }
};

export const getAllSubCategories = categoryName => async dispatch => {
  try {
    dispatch({
      type: GET_SUB_CATEGORIES_REQUEST
    });
    const config = {
      headers: {
        "Content-Type": "application/json"
      }
    };

    let query = {
      filters: {},
      populate: ["category"]
    };

    if (categoryName) {
      query.filters.category.name = { $eq: categoryName };
    }
    const queryString = qs.stringify(query, {
      encodeValuesOnly: true
    });

    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/sub-categories/?${queryString}`, config);

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

    return response.data;
  } catch (error) {
    dispatch({
      type: GET_SUB_CATEGORIES_FAIL,
      payload: error.response.data
    });
  }
};