Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: Add a `mapParamsToProps` to `withQueryParams` #69

Open
leonelgalan opened this issue Jan 14, 2020 · 0 comments
Open

Suggestion: Add a `mapParamsToProps` to `withQueryParams` #69

leonelgalan opened this issue Jan 14, 2020 · 0 comments

Comments

@leonelgalan
Copy link

@leonelgalan leonelgalan commented Jan 14, 2020

Coming from React-Redux's connect it felt limiting that the props had to be called query and setQuery. Having a mapParamsToProps(query, setQuery, ownProps?) allows complex configurations without rewriting components to use query and setQuery.

If there is interest, I'm willing to write a proper PR, but I would like guidelines on how to do it? As a breaking change or as a second HOC?

I apologize for my mix of JS and TS, I wrote my withQueryParams in JSX, but wanted to use the example in the README:

import React from 'react';
import {
  useQueryParams,
  StringParam,
  NumberParam,
  ArrayParam,
} from 'use-query-params';

// withQueryParams.jsx
const withQueryParams = (paramConfigMap, mapParamsToProps) => (WrappedComponent) => {
  const Component = (props) => {
    const [query, setQuery] = useQueryParams(paramConfigMap);
    return <WrappedComponent {...mapParamsToProps(query, setQuery, props)} {...props} />;
  };
  Component.displayName = `withQueryParams(${WrappedComponent.displayName ||
    WrappedComponent.name ||
    'Component'})`;
  return Component;
};

// example.tsx
const WithQueryParamsExample = ({
  x: num,
  q: searchQuery,
  filters = [],
  onChange = () => {},
  onChangeAll = () => {},
}: any) => {
  return (
    <div>
      <h1>num is {num}</h1>
      <button onClick={onChange}>Change</button>
      <h1>searchQuery is {searchQuery}</h1>
      <h1>There are {filters.length} filters active.</h1>
      <button onClick={onChangeAll}>Change All</button>
    </div>
  );
};

const mapParamsToProps = (query, setQuery) => {
  const { x, q, filters } = query;
  return {
    x,
    q,
    filters,
    onChange: () => setQuery({ x: Math.random() }),
    onChangeAll: () =>
      setQuery({ x: Math.random(), filters: [...filters, 'foo'], q: 'bar' }, 'push'),
  };
};

export default withQueryParams(
  {
    x: NumberParam,
    q: StringParam,
    filters: ArrayParam,
  },
  mapParamsToProps,
)(WithQueryParamsExample);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant
You can’t perform that action at this time.