relatedProductSlice.js
1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
import qs from "qs";
export const fetchRelatedProduct = createAsyncThunk(
    "RelatedProductSlice/fetchRelatedProduct",
    async () => {
        const query = {
            populate: [
                "image",
                "productCategory.Banner",
            ],
        };
        const queryString = qs.stringify(query, {
            encodeValuesOnly: true,
        });
        const endpoint = `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/related-products?${queryString}`;
        const response = await axios.get(endpoint);
        return response.data.data;
    }
);
const RelatedProductSlice = createSlice({
    name: "Product Detail",
    initialState: {
        status: "idle",
        data: [],
        error: null,
    },
    reducers: {},
    extraReducers: (builder) => {
        builder
            .addCase(fetchRelatedProduct.pending, (state) => {
                state.status = "loading";
            })
            .addCase(fetchRelatedProduct.fulfilled, (state, action) => {
                state.status = "succeeded";
                state.data = action.payload;
            })
            .addCase(fetchRelatedProduct.rejected, (state, action) => {
                state.status = "failed";
                state.error = action.error.message;
            });
    },
});
export default RelatedProductSlice.reducer;