Home > Enterprise >  Can't get parameters from url with Redux ownProps
Can't get parameters from url with Redux ownProps

Time:04-04

So I'm having an error message - Uncaught TypeError: Cannot read properties of undefined (reading 'params')

AddOrUpdateProduct.js

function mapStateToProps(state, ownProps) {
    const productId = ownProps.match.params.productId;
    const product =
        productId && state.productListReducer.length > 0
            ? getProductById(state.productListReducer, productId)
            : {}
    return {
        product: product,
        products: state.productListReducer,
        categories: state.categoryListReducer
    }
}

App.js

        <Routes>
          <Route path="/" exact element={<Dashboard />} />
          <Route path="/product" exact element={<Dashboard />} />
          <Route path="/saveproduct/:productId" element={<AddOrUpdateProduct />} />
          <Route path="/cart" exact element={<CartDetail />} />
        </Routes>

I'm trying to get the productid in the url with 'ownProps.match.params.productId'

CodePudding user response:

No react expert here but I think you need to use withRoute when exporting the component, something like this

export default withRouter(AddOrUpdateProduct);

CodePudding user response:

Issue

In react-router-dom@6 there are no longer route props. If you need to access the productId route param then you will need to create a Higher Order Component to access the route props and inject them as props into your class component.

Solution

Create a custom withRouter component:

import { useParams } from 'react-router-dom';

const withRouter = Component => props => {
  const params = useParams();
  return <Component {...props} params={params} />;
}

Wrap and decorate the AddOrUpdateProduct component so it has the params injected as a prop.

function mapStateToProps(state, ownProps) {
  const productId = ownProps.params.productId;
  const product =
    productId && state.productListReducer.length > 0
      ? getProductById(state.productListReducer, productId)
      : {};

  return {
    product,
    products: state.productListReducer,
    categories: state.categoryListReducer
  };
}

export default connect(mapStateToProps)(withRouter(AddOrUpdateProduct));
  • Related