0

So I have this reducer that I would like to update

import { fromJS } from 'immutable';
const initialState = fromJS({
  searchParams: {
    limit: 100,
    page: 1,
    order_by: 'name',
    filters: {
      and_keywords : []
    }
  },
})

when the action is triggered I would like to push an object into the array of and_keywords. What I have done so far is this

case ADD_KEYWORDS:
return state
    .setIn(['searchParams', 'filters', 'and_keywords'], '123');

I also tried

case ADD_KEYWORDS:
return state
    .updateIn(['searchParams', 'filters', 'and_keywords'], arr => arr.push('123'))

basing from the documents in https://facebook.github.io, but I can't seem to make it work. No changes have been made after executing this command

2
  • Immutable objects don't modify in place, you have to reassign the thing you're modifying. So just add state = to the start of your lines and it should work. Commented Sep 27, 2017 at 3:43
  • I already have function homePageReducer(state = initialState, action) { just did not include it as I only posted a snippet of my code Commented Sep 27, 2017 at 3:56

1 Answer 1

1

Your updateIn version should work:

const Immutable = require('immutable')

const initialState = Immutable.fromJS({
  searchParams: {
    limit: 100,
    page: 1,
    order_by: 'name',
    filters: {
      and_keywords : []
    }
  },
})

const newState = initialState.updateIn(['searchParams', 'filters', 'and_keywords'], arr => arr.push('123'))

console.log(newState)

Your setIn version code should work as well with a small modification:

const Immutable = require('immutable')


const initialState = Immutable.fromJS({
  searchParams: {
    limit: 100,
    page: 1,
    order_by: 'name',
    filters: {
      and_keywords : []
    }
  },
})

const newState = initialState.setIn(['searchParams', 'filters', 'and_keywords'], initialState.getIn(['searchParams', 'filters', 'and_keywords']).push('123'))

console.log(newState)

Both should output:

Map { "searchParams": Map { "limit": 100, "page": 1, "order_by": "name", "filters": Map { "and_keywords": List [ "123" ] } } }
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah. It was another bug on my end that caused the issue. Accepted the answer still for reference for others to use. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.