0

In this code, when i change the value of state in the setMessage() reducer to action.payload, the changes aren't getting picked up by the selectors.

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: null,
  type: null
}

export const messageSlice = createSlice({
  name: 'message',
  initialState: initialState,
  reducers: {
    setMessage: (state, action) => {
      state = action.payload                         //not working
    },
    clearMessage: state => {
      state = initialState                           //not working
    }
  }
})

but if i change the "value" or "type" field of the message state instead of changing the whole object, the selectors are able to pick up the changes and everything works fine:

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: null,
  type: null
}

export const messageSlice = createSlice({
  name: 'message',
  initialState: initialState,
  reducers: {
    setMessage: (state, action) => {
      state.value = action.payload.value           //works
      state.type = action.payload.type             //works
    },
    clearMessage: state => {
      state.value = null                           //works
      state.type = null                            //works
    }
  }
})
Akshay Dagar
  • 13
  • 1
  • 2
  • Does this answer your question? [Does JavaScript pass by reference?](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference) – Konrad Jan 04 '23 at 14:05

1 Answers1

0

There are no pointers in JavaScript. When = is used with a variable a new value is assigned to it, not to a memory address

function setMessage(state) {
  state = {
    x: 5
  }
}

let state = {
  x: 3
}
setMessage(state)

console.log(state)

function setMessage(state) {
  state.x = 5
}

let state = {
  x: 3
}
setMessage(state)

console.log(state)
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • @rook218 [difference between pointers and references](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable) – Konrad Jan 04 '23 at 13:55
  • 1
    So that means the "state" parameter in the reducer is a reference to the actual state {v1,t1} and when I do state.value = v2 the object gets updated to {v2,t1}, but when I do state = {v2,t1} then the reference "state" points to some other position ? – Akshay Dagar Jan 04 '23 at 14:05