2024-06-27 16:06:39 +02:00
|
|
|
import { createSelector, createSlice, PayloadAction } from '@reduxjs/toolkit';
|
|
|
|
import { Id, Product } from '@/lib/product';
|
|
|
|
import uuid from "react-native-uuid";
|
|
|
|
import { RootState } from '@/app/store';
|
|
|
|
|
|
|
|
const initialState = {
|
|
|
|
products: [] as Product [],
|
|
|
|
}
|
|
|
|
|
|
|
|
const productsState = createSlice({
|
|
|
|
name: 'products-slice',
|
|
|
|
initialState,
|
|
|
|
reducers: {
|
|
|
|
createProduct(state, action: PayloadAction<Product>) {
|
|
|
|
if (!state) {
|
|
|
|
return initialState
|
|
|
|
}
|
|
|
|
const product = action.payload;
|
|
|
|
if (!product.id) product.id = uuid.v4().toString();
|
|
|
|
state.products = [...state.products, action.payload];
|
|
|
|
return state;
|
|
|
|
},
|
|
|
|
updateProduct(state, action: PayloadAction<Product>) {
|
|
|
|
if (!state) return initialState;
|
|
|
|
const product = action.payload;
|
|
|
|
if (!product.id) {
|
|
|
|
throw new Error("Product has no ID");
|
|
|
|
}
|
|
|
|
state.products = state.products.map((prod) => {
|
|
|
|
return prod.id === product.id ? product : prod;
|
|
|
|
})
|
|
|
|
return state;
|
|
|
|
},
|
|
|
|
deleteProduct(state, action: PayloadAction<Id>) {
|
|
|
|
if (!state) return initialState;
|
|
|
|
state.products = state.products.filter((prod) => {
|
|
|
|
prod.id !== action.payload;
|
|
|
|
})
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
export const selectProducts = (state : RootState) => {
|
2024-06-28 23:53:48 +02:00
|
|
|
return state.products;
|
2024-06-27 16:06:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export const actions = {
|
|
|
|
...productsState.actions
|
|
|
|
};
|
|
|
|
|
|
|
|
export const {
|
|
|
|
createProduct,
|
|
|
|
updateProduct,
|
|
|
|
deleteProduct,
|
|
|
|
} = productsState.actions;
|
|
|
|
|
|
|
|
export default productsState.reducer;
|