Guest User

Untitled

a guest
Jan 20th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. import * as React from 'react';
  2. import {Component} from "react";
  3. import * as queryString from 'qs';
  4. import {RouteComponentProps} from "react-router";
  5. import {omit} from 'underscore';
  6.  
  7. const stringifyQuery = (query: object): string => {
  8. return queryString.stringify(query)
  9. };
  10.  
  11. const parseQuery = (query: string) => {
  12. return queryString.parse(query, { ignoreQueryPrefix: true });
  13. };
  14.  
  15. export interface State<Schema extends object, SchemaKey extends keyof Schema> {
  16. filters: Schema;
  17. submitFilters: () => void;
  18. resetFilters: () => void;
  19. changeFilter: (key: SchemaKey, value: Schema[SchemaKey]) => void;
  20. }
  21.  
  22. interface Props<
  23. Schema extends object,
  24. SchemaKey extends keyof Schema
  25. > extends Pick<RouteComponentProps<{}>, 'location' | 'history'> {
  26. children(props: State<Schema, SchemaKey>): JSX.Element;
  27. }
  28.  
  29. export class FilterProvider<
  30. Schema extends object,
  31. SchemaKey extends keyof Schema
  32. > extends Component<
  33. Props<Schema, SchemaKey>,
  34. State<Schema, SchemaKey>
  35. > {
  36. constructor(props) {
  37. super(props);
  38. this.state = {
  39. filters: parseQuery(this.props.location.search) as Schema,
  40. submitFilters: this.submitFilters,
  41. resetFilters: this.resetFilters,
  42. changeFilter: this.changeFilter,
  43. }
  44. }
  45.  
  46. submitFilters = () => {
  47. this.props.history.push(this.props.location.pathname + '?' + stringifyQuery(this.state.filters));
  48. };
  49.  
  50. resetFilters = () => {
  51. this.setState({filters: {} as Schema});
  52. this.props.history.push(this.props.location.pathname);
  53. };
  54.  
  55. changeFilter = (key: SchemaKey, value: Schema[SchemaKey]) => {
  56. const filters: Schema = value
  57. ? Object.assign(this.state.filters, {[key]: value})
  58. : omit(this.state.filters, key);
  59.  
  60. this.setState({filters: filters});
  61. };
  62.  
  63. render() {
  64. return this.props.children(this.state);
  65. }
  66. }
Add Comment
Please, Sign In to add comment