0

I'm finding my way around the Redux echosystem, and I came across the following sutuation: Suppose I have a React component which should be connected to a redux state part using a selector, but this part does not exist yet (undefined). So, when running it I get a "get on undefined" error. Is it possible to somehow define and connect the selector to the component, even though the state part does not exist yet?

I'm using reselect for creating the selector, this is a workaround I've used to avoid throwing the error:

import { createSelector } from 'reselect';

const selectLogin = (state) => state

const loginDataSelector = () => createSelector(
  selectLogin,
  (authState) => authState.get("auth")?
   authState.get("auth").get('loginData'):undefined
);

export {
  loginDataSelector
};

By this way, the selectLogin selector seems to monitor the entire state tree. Is there a better way to do this, or is there a best practise for selectors with an undefined (=not set yet) state part?

  • 1
    what if you set that piece of state to some default value initially? – Balázs Édes Jul 27 '17 at 07:38
  • This means that I should use a reducer for this state part, right? This seems a little too much to me, since I only need to read the state part, and not write it (from this component). Also, there is a reducer for this state part in another component, is has just not been called yet. A related question that arises is if there is a way to connect an already existing component to a state part AFTER it has been initialized/rendered, etc. This would avoid the "non existing state" problem. – Matt Clouds Jul 27 '17 at 07:55

1 Answers1

1

You can use ES6 default values to work around this issue.

Also not the use of getIn that allows you to safely access deep properties

import { createSelector } from 'reselect';
import { Map } from 'immutable';

const selectLogin = (state) => state

const loginDataSelector = createSelector(
  selectLogin,
  (authState = Map()) => authState.getIn(["auth", "loginData"])
);
thedude
  • 9,388
  • 1
  • 29
  • 30