Home > Blockchain >  can't delete object from redux store
can't delete object from redux store

Time:10-03

import { createSlice } from "@reduxjs/toolkit";

const transactionSlice = createSlice({
    name: 'transactions',
    initialState: [
        {id: 1, text: 'shady', amount: 55},
        {id: 2, text: 'shady', amount: 55},
        {id: 3, text: 'shady', amount: 55}
    ],
    reducers: {
        addTransaction: (state, action) => {
            const newTransaction = {
                id: Math.floor(Math.random() * 100000),
                text: action.payload.text,
                amount:  action.payload.amount
            }
            state.push(newTransaction);
        },
        deleteTransaction: (state, action) => ({
            ...state,
            transactions: state.transactions.filter(transaction => transaction.id !== action.payload.id)
        })
    }
})

export const { addTransaction, deleteTransaction } = transactionSlice.actions;
export default transactionSlice.reducer;

I want to delete a transaction from the store and its return TypeError: can't access property "filter", state.transactions is undefined

CodePudding user response:

You are getting this because you don't have any key named transactions in your state.

You can resolve this by updating your initialStatevalue in the createSlice method to

initialState: {
    transactions:[
        {id: 1, text: 'shady', amount: 55},
        {id: 2, text: 'shady', amount: 55},
        {id: 3, text: 'shady', amount: 55}
    ]
}

CodePudding user response:

The state of the slice is an array - for example, you push to the state to add a transaction. Filter the state to remove one:

    deleteTransaction: (state, action) =>
        state.filter(transaction => transaction.id !== action.payload.id)
  • Related