Accessing a selector value in ReactJS with ImmutableJS

394 views Asked by At

I am using a memoized selector via the react reselect library and I'm having trouble accessing the state value to see if it's set or not.

I would like to be able to do something like this to check:

const room = selectRoomById('roomId1');
if (room) {
    console.log('this room exists in the global.rooms store');
}

The store looks like this:

global: {
    rooms: {
        "roomId1": {
            "name": "room 1"
        },
        "roomId2": {
            "name": "room 2"
        }
    }
}

Here's what mapStateToProps (this part is working) and my selectors look like:

const mapStateToProps = (state, props) => {
  return createStructuredSelector({
    room: selectRoomById(props.params.roomId)
  });
}

Selectors:

const selectGlobal = () => (state) => state.get('global');
const selectRoomById = (roomId) => createSelector(
  selectGlobal(),
  (globalState) => globalState.getIn(['rooms', roomId])
);

When I do

console.log(selectRoomById('roomId1'));

I get a function back, and I'm not able to get the value I'm looking for. I think this is because I'm using createSelector but I'm not sure. Does anyone know how I could access the value of the selector?

1

There are 1 answers

0
Dillon S. On BEST ANSWER

I had to use toJS() in my selector...

change

(globalState) => globalState.getIn(['rooms', roomId])

to

(globalState) => globalState.getIn(['rooms', roomId]).toJS()

ImmutableJS was adding a layer of complication here.

Update:

Rather than using toJS (which is costly) I'm going to just use .get and .getIn in the component