user17016241
user17016241

Reputation:

How to return an object in Redux?

I have a button that, when clicked, sends an object [ Dispatch(ADDS(myObject) ], but my [ Reducer ] does not return the object as the first ( index 0 ), it returns the first item ( empty ) because the ( InitialState ) it is set to ( empty ). How do I return the object as ( Index 0 ) ?

Console.log

console.log - Prinscreen

My UI.js

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

export const slice = createSlice({
    name: 'initial',
    
    initialState : {
        product: [],
    },
    
    reducers: {
        ADDS(state, actions) {
            return {
                ...state, 
                product: actions.payload,
            } 
        }
    }
});

export const { ADDS } = slice.actions;

export default slice.reducer;

Thanks

Upvotes: 0

Views: 706

Answers (2)

Kanti vekariya
Kanti vekariya

Reputation: 697

here destructure your reducer response like this product: [...state.product, actions.payload]

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

export const slice = createSlice({
    name: 'initial',
    
    initialState : {
        product: [],
    },
    
    reducers: {
        ADDS(state, actions) {
            return{
              ...state,
              product: [...state.product, actions.payload]
            }
        }
    }
});

export const { ADDS } = slice.actions;

export default slice.reducer;

Upvotes: 1

David Bradshaw
David Bradshaw

Reputation: 13077

You are currently replacing your array with your object in the reducer.

It’s not quite clear what you’re trying to achieve here, do you just want to add every new dispatched object to the array?

If so you need to something like this

product: state.push(actions.payload),

Upvotes: 0

Related Questions