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) { 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) { 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) { if (!state) return initialState; state.products = state.products.filter((prod) => { prod.id !== action.payload; }) return state; } } }); export const selectProducts = (state : RootState) => { return state.products } export const actions = { ...productsState.actions }; export const { createProduct, updateProduct, deleteProduct, } = productsState.actions; export default productsState.reducer;