categoriesAction.js 1.87 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 => {
  console.log("here >");
  try {
  console.log("here >>");

    dispatch({
      type: GET_CATEGORIES_REQUEST
    });

    const config = {
      headers: {
        "Content-Type": "application/json"
      }
    };
    const query = {
      populate: ["image"]
    };

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

    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/categories?${queryString}`, config);
    console.log("response > ", response);
    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"
      }
    };

    const query = {
      filters: {
        category: {
          name: { $eq: categoryName }
        }
      },
      populate: ["category"]
    };

    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
    });
  }
};