Why can’t I chain state.get(‘something’).filter with immutable.js?

What am I doing wrong?

I want to filter the steps key inside my state using get('..') and filter but I can’t manage to do it.

I have this function:

function visibleSteps(state) {
  return state.get('steps').filter((step) => {
    return step.display
  })
}

When tested with this example:

describe('visibleSteps', () => {
  it('should show the steps with display true and their title', () => {
     const state = Map({
        steps: {
            0: {
                display: false
            },
            1: {
                display: true,
                title: "A title"
            },
            2: {
                display: true,
            },
            3: {
               display: false,
            }
        }
    })

    expect(visibleSteps(state).size).to.equal(2)
  })
})

I get this error:

TypeError: state.get(...).filter is not a function

How would the man do this?

Answer

You are getting this error because the value of steps is a plain object. Objects don’t have a .filter method. If you want the value to be a Map, you can explicitly create it:

const state = Map({
  steps: Map({
    // ...
  })
});

Similarly for the most inner objects. If you want a nested JS object/array to be deeply converted to an Immutable Maps and Lists, you can use immutable.fromJS.

Leave a Reply

Your email address will not be published. Required fields are marked *