37980-vm/frontend/src/stores/wishlistSlice.ts
2026-01-30 17:40:21 +00:00

111 lines
3.4 KiB
TypeScript

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
import { fulfilledNotify, rejectNotify, resetNotify } from "../helpers/notifyStateHandler";
interface WishlistState {
wishlist: any[]
loading: boolean
count: number
notify: {
showNotification: boolean
textNotification: string
typeNotification: string
}
}
const initialState: WishlistState = {
wishlist: [],
loading: false,
count: 0,
notify: {
showNotification: false,
textNotification: '',
typeNotification: 'warn',
},
}
export const fetchWishlist = createAsyncThunk('wishlist/fetch', async (query: any) => {
const params = new URLSearchParams(query).toString();
const result = await axios.get(`wishlists?${params}`)
return result.data;
})
export const addToWishlist = createAsyncThunk('wishlist/add', async (productId: string, { rejectWithValue }) => {
try {
const result = await axios.post('wishlists', { data: { product: productId } })
return result.data
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
})
export const removeFromWishlist = createAsyncThunk('wishlist/remove', async (id: string, { rejectWithValue }) => {
try {
await axios.delete(`wishlists/${id}`)
return id
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
})
export const toggleWishlist = createAsyncThunk('wishlist/toggle', async (productId: string, { getState, dispatch }) => {
const state = getState() as any;
const existing = state.wishlist.wishlist.find((item: any) => item.product?.id === productId || item.productId === productId);
if (existing) {
await dispatch(removeFromWishlist(existing.id));
} else {
await dispatch(addToWishlist(productId));
}
await dispatch(fetchWishlist({}));
})
export const wishlistSlice = createSlice({
name: 'wishlist',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchWishlist.pending, (state) => {
state.loading = true
resetNotify(state);
})
builder.addCase(fetchWishlist.fulfilled, (state, action) => {
state.wishlist = action.payload.rows;
state.count = action.payload.count;
state.loading = false
})
builder.addCase(fetchWishlist.rejected, (state, action) => {
state.loading = false
rejectNotify(state, action);
})
builder.addCase(addToWishlist.pending, (state) => {
state.loading = true
resetNotify(state);
})
builder.addCase(addToWishlist.fulfilled, (state) => {
state.loading = false
fulfilledNotify(state, 'Product added to wishlist');
})
builder.addCase(addToWishlist.rejected, (state, action) => {
state.loading = false
rejectNotify(state, action);
})
builder.addCase(removeFromWishlist.fulfilled, (state, action) => {
state.wishlist = state.wishlist.filter(item => item.id !== action.payload);
state.count = state.count - 1;
fulfilledNotify(state, 'Product removed from wishlist');
})
},
})
export default wishlistSlice.reducer