1

I am facing a problem using mapStateToProps(state, ownProps) in order to plug query parameters from my URL to the props of my component.

I am trying to use my URL as a searchState as suggested by Dan Abramov answer in this question : How to sync Redux state and url query params

The problem is, I cam not able to access query params from ownProps.

My URL is, for example : http://localhost:3000/courses?language=en&page=3 and I would like to access the page number as a prop.

I think ownProps does not work for query parameters (i.e [...]?language=en&page=3). I tried this kind of stuff but it does not seem to work :

[...]
console.log(props.pageNumber)
[...]
const mapStateToProps = (state, ownProps) => {
  return {
    pageNumber: ownProps.match.params.page
  }
}

Do you have any idea on how I could access my page number as an ownProp coming from my URL ?

Thanks in advance.

Sylvain
  • 53
  • 1
  • 6

2 Answers2

1

Query parameters are not part of the params in match.params. You have to access them yourself from the location and parse them using the browser's URLSearchParams or a helper like qs. There's a demo in the docs that might help.

Here's the hook from that demo:

// A custom hook that builds on useLocation to parse
// the query string for you.
function useQuery() {
  return new URLSearchParams(useLocation().search);
}

Inside your component, you can access the query parameters with this hook and use them as arguments for a selector function.

const query = useQuery();

// query parameters might be `null`
const language = query.get("language") ?? "en";

// they are always `string` instead of `number`
const page = parseInt(query.get("page") ?? "1");

// can use these values to select from the store
const courses = useSelector(selectCourses(language, page))

You could parse the location in mapStateToProps if you wanted to. But Dan's answer is from 2016 and nowadays React hooks make more sense, in my option at least.

Linda Paiste
  • 20,442
  • 2
  • 16
  • 40
1

I would suggest to access query parameters inside componentDidMount or any method which runs on mounting of any component by using this.props.location.search instead of accessing in mapStateToProps.