71 lines
1.9 KiB
TypeScript
71 lines
1.9 KiB
TypeScript
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
|
|
import { RootState } from "../store";
|
|
import axios from "../../api/axios";
|
|
import { favorites } from "../../api-bodies/MockData";
|
|
|
|
interface FavoritesState {
|
|
favorites: string[];
|
|
}
|
|
|
|
const initialState: FavoritesState = {
|
|
favorites: [],
|
|
};
|
|
|
|
export const favoritesSlice = createSlice({
|
|
name: "favorites",
|
|
initialState,
|
|
reducers: {},
|
|
extraReducers(builder) {
|
|
builder
|
|
.addCase(fetchFavorites.fulfilled, (state, action) => {
|
|
state.favorites = action.payload;
|
|
})
|
|
.addCase(addFavorite.fulfilled, (state, action) => {
|
|
state.favorites.push(action.payload);
|
|
})
|
|
.addCase(removeFavorite.fulfilled, (state, action) => {
|
|
const index = state.favorites.indexOf(action.payload);
|
|
state.favorites.splice(index, 1);
|
|
});
|
|
},
|
|
});
|
|
|
|
export const fetchFavorites = createAsyncThunk(
|
|
"favorites/fetchFavorites",
|
|
async (uuid: string) => {
|
|
if (uuid) {
|
|
const response = await axios.get(`/users/${uuid}/favourites`);
|
|
return response.data.userIds;
|
|
} else {
|
|
return favorites;
|
|
}
|
|
}
|
|
);
|
|
export const addFavorite = createAsyncThunk(
|
|
"favorites/addFavorite",
|
|
async (ids: { userId: string; toBeAdded: string }) => {
|
|
if (ids.userId) {
|
|
await axios.post(
|
|
`/users/${ids.userId}/favourites`,
|
|
JSON.stringify({ userId: ids.toBeAdded })
|
|
);
|
|
return ids.toBeAdded;
|
|
} else {
|
|
return ids.toBeAdded;
|
|
}
|
|
}
|
|
);
|
|
export const removeFavorite = createAsyncThunk(
|
|
"favorites/removeFavorite",
|
|
async (ids: { userId: string; toBeRemoved: string }) => {
|
|
if (ids.userId) {
|
|
await axios.delete(`/users/${ids.userId}/favourites/${ids.toBeRemoved}`);
|
|
return ids.toBeRemoved;
|
|
} else {
|
|
return ids.toBeRemoved;
|
|
}
|
|
}
|
|
);
|
|
export const selectFavorites = (state: RootState) => state.favorites.favorites;
|
|
export default favoritesSlice.reducer;
|