Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as React from 'react';
- import {Component} from "react";
- import * as queryString from 'qs';
- import {RouteComponentProps} from "react-router";
- import {omit} from 'underscore';
- const stringifyQuery = (query: object): string => {
- return queryString.stringify(query)
- };
- const parseQuery = (query: string) => {
- return queryString.parse(query, { ignoreQueryPrefix: true });
- };
- export interface State<Schema extends object, SchemaKey extends keyof Schema> {
- filters: Schema;
- submitFilters: () => void;
- resetFilters: () => void;
- changeFilter: (key: SchemaKey, value: Schema[SchemaKey]) => void;
- }
- interface Props<
- Schema extends object,
- SchemaKey extends keyof Schema
- > extends Pick<RouteComponentProps<{}>, 'location' | 'history'> {
- children(props: State<Schema, SchemaKey>): JSX.Element;
- }
- export class FilterProvider<
- Schema extends object,
- SchemaKey extends keyof Schema
- > extends Component<
- Props<Schema, SchemaKey>,
- State<Schema, SchemaKey>
- > {
- constructor(props) {
- super(props);
- this.state = {
- filters: parseQuery(this.props.location.search) as Schema,
- submitFilters: this.submitFilters,
- resetFilters: this.resetFilters,
- changeFilter: this.changeFilter,
- }
- }
- submitFilters = () => {
- this.props.history.push(this.props.location.pathname + '?' + stringifyQuery(this.state.filters));
- };
- resetFilters = () => {
- this.setState({filters: {} as Schema});
- this.props.history.push(this.props.location.pathname);
- };
- changeFilter = (key: SchemaKey, value: Schema[SchemaKey]) => {
- const filters: Schema = value
- ? Object.assign(this.state.filters, {[key]: value})
- : omit(this.state.filters, key);
- this.setState({filters: filters});
- };
- render() {
- return this.props.children(this.state);
- }
- }
Add Comment
Please, Sign In to add comment