Reselect - Props undefined in selector

1.8k Views Asked by At

I have one container with its selectors and It renders another container that has its other selectors.

The problem with that is that the second one, props are undefined and it breaks everything.

Here's the code (where props are undefined in the second selector):

selectProductsState props returning undefined.

One selector:

const selectProductsState = () => ({ products }, props) => { return { products, props } };

const getCurrentProductFromParams = () => createSelector(
  selectProductsState(),
  getProductsItems(),
  ({ props }, items) => {
    const id = extractId(props.params);

    return items[id];
  }
);

ProductContainer:

class ProductPage extends React.Component {

    render() {
        return (<OtherContainer />)
    }
}

const mapStateToProps = createStructuredSelector({
  hasLoadingErrors: getHasLoadingErrors(),
  productNotFound: getProductNotFound(),
  product: getProduct(),
  getCurrentProductFromParams
});

Another container has his own selectors.

How can I fix that?

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

The problem was with the params prop passed from react-router to the ProductPage container.

So params it's not passed down to the OtherContainer automatically, therefore, params it's undefined

The solution is passing manually the prop to OtherContainer:

class ProductPage extends React.Component {
    render() {
        return (<OtherContainer params={this.props.params} />)
    }
}

const mapStateToProps = createStructuredSelector({
  hasLoadingErrors: getHasLoadingErrors(),
  productNotFound: getProductNotFound(),
  product: getProduct(),
  getCurrentProductFromParams
});
1
On

It probably breaks because you try to extract a props property from an undefined object in your result function params ({ props }).

If receiving undefined from selectProductsState is an acceptable use case, you should simply rewrite the result function in order to take the edge case into account. Eg:

(productsState, items) => {
    if(productsState === undefined){
        return undefined;
    }
    const id = extractId(productsState.props.params);
    return items[id];
 }