-2

I am passing a value from my redux store to a function

itnerface SelectedProps {
    [key: string]: {
        date: number,
        bar: string[]
    }
}

type FooState = {
    selected: SelectedProps
};

const initialState: FooState = {selected: {}}

    
export const giftSlice = createSlice({
    name: 'whatever',
    initialState,
    reducers: {
        thisIsAnAction: (state, action: PayloadAction<string>) => {
            const thisGivesMeTheProxyObject = state.foo[action.key].bar 
            console.log(thisGivesMeTheProxyObject)
        }
    }
})

Proxy { : (1) […], : {…} }

What is this Proxy object, and why is it not an array?

four-eyes
  • 10,740
  • 29
  • 111
  • 220

2 Answers2

0

The documentation for createSlice says:

This object will be passed to createReducer, so the reducers may safely "mutate" the state they are given.

The documentation for createReducer says:

To make things easier, createReducer uses immer to let you write reducers as if they were mutating the state directly. In reality, the reducer receives a proxy state that translates all mutations into equivalent copy operations.

So you get a proxy for an array instead of a raw array so you can write simple code that mutates the array while still allowing the reducer to return a whole new object instead of a mutated version of the original object.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You are probably using redux-toolkit

When using createSlice, it automatically wrap your reducer with immerjs produce function.

produce allow you to resolve the next state by mutating the state without actually mutating the state in your store. It does so by wrapping the state in a Proxy that will catch all the mutation you are doing in the reducer. (see Proxy for more info)

If you want to debug your state you can use the function current exported by immer (e.g console.log(current(thisGivesMeTheProxyObject)))

shantr
  • 724
  • 1
  • 6