Use React high-level components to store React state in URL query

Use React high-level components to store React state in URL query

Use the React higher-order component to store the React State in URL query (routing parameters)

Use the React higher-order component to store the React State in URL query (routing parameters)

Demo

^_^ This is demo of using sync-query in antd-design.

There is only three lines of code.

// import
import { syncQueryHOC } from "sync-query";
// use syncQueryHOC
const MyComponentEnhance = syncQueryHOC(MyComponent, ['searchInput', 'pagination'], 'fetch');
<MyComponentEnhance></MyComponentEnhance>
//...

More about the Demo

Once we did this, there are powerful features below.

Feature

  • auto store react state in url query (URLSearchParam)
  • auto call 'fetch' if react state is detected change.
  • auto init react state from url query (URLSearchParam)
  • zero dependency, only 2.8kb gzipped size.
  • support TypeScript decorator

Installation

yarn add sync-query

npm i --save sync-query

Usage

Use TypeScript Decorator

import { SyncQueryFactory, syncQueryCb } from "sync-query";

@SyncQueryFactory(['searchInput', 'pagination']) // Listen to searchInput or Pagination changes when synchronized to URL Query
export class MyComponent extends Component {
    this.state = {
        searchInput: 'hello world',
        pagination: {
        },
    }
    @syncQueryCb(['searchInput']) // The fetch function is called to listen for a change in searchInput
    fetch() {
        // network fetch...
    }
}

Use ES6 React HOC

import { syncQueryHOC } from "sync-query";

export class MyComponent extends Component {
    fetch() {
        // network fetch...
    }
}

export const MyComponentEnhance = 
    syncQueryHOC(
        MyComponent,
        ['searchInput', 'pagination'], // Listen to searchInput or Pagination changes when synchronized to URL Query
        'fetch',
        {
            callbackDeps: ['searchInput'], // The fetch function is called to listen for a change in searchInput
            wait: 600, // debounce,600ms
        }
    );

Note: The SyncQueryFactory decorator factory and syncQueryHOC are placed closest to the MyComponent

Manual synchronization

The library automatically stores state to the URL query and triggers the callback function.

The approach of shutting down is to add 'disableAutoSync' in the class decorator configuration.

The method for manual synchronization is (this as SyncQueryHost).Triggersync).

The sample code is as follows:

@SyncQueryFactory(
    ['pagination', 'searchInput'],
    'fetch',
    {
        disableAutoSync: true
    }
)
class MyComponent extends Component {
    onHandlePageChange(current) {
        this.setState(
            {
                pagination: {
                    ...this.state.pagination,
                    current,
                },
            },
            (this as SyncQueryHost).triggerSync
        );
    }
}

API

syncQueryHOC

Receive a React component that returns a component with the ability to synchronize state to routing parameters

syncQueryHOC(WrappedComponent, stateList: string[], callbackName?:string, config?:SyncQueryConfig): EnhanceComponent

  • WrappedComponent: The original component is decorated
  • stateList: Pass an array, and the value of the state corresponding to the key will be listened to
  • callbackName?: The effect method is triggered when changes are heard
  • config?: SyncQueryConfig
type SyncQueryConfig = {
    wait: number,                           // The wait time for the debounce,, the unit is ms
    callbackDeps?: string[],                // CallbackDeps holds an array of state keys. When the value of the corresponding key in the state changes, the callback (network request, etc.) will be called.
                                            // When callbackDeps is not passed in, the default listener is equal to stateList
    parser?: IQueryParser,                  // Parser: Used to parse the routing parameter query to state. Default is JSON.parse
    stringify?: IQueryStringify,            // Generator: Used to generate the query string corresponding to state. Default is JSON.Stringify
}

SyncQueryFactory

SyncQueryFactory is a Decorator Factory, used in Typescript

SyncQueryFactory(stateList: string[], callbackName?:string, config?:SyncQueryConfig)

Note that a class decorator factory, SyncQueryFactory, and a method decorator, syncQueryCb, can be used together. SyncQueryHOC, a higher-order component, and the first two should be avoided as much as possible.

  • stateList: Pass an array, and the value of the state corresponding to the key will be listened to
  • callbackName?: The 'callbackName' method is triggered when a change is heard
  • config?: SyncQueryConfig
type SyncQueryConfig = {
    wait: number,                           // The wait time for the debounce,, the unit is ms
    callbackDeps?: string[],                // CallbackDeps holds an array of state keys. When the value of the corresponding key in the state changes, the callback (network request, etc.) will be called.
                                            // When callbackDeps is not passed in, the default listener is equal to stateList
    parser?: IQueryParser,                  // Parser: Used to parse the routing parameter query to state. Default is JSON.parse
    stringify?: IQueryStringify,            // Generator: Used to generate the query string corresponding to state. Default is JSON.Stringify
}

SyncQueryFactory Code is as follows:

function SyncQueryFactory(stateList: string[], callbackName?:string, config?:SyncQueryConfig) {
    return function(WrappedComponent) {
        return syncQueryHOC(WrappedComponent, stateList, callbackName, config);
    }
}

syncQueryCb

The syncQueryCb is a method decorator, used in conjunction with the SyncQueryFactory

syncQueryCb(callbackDeps?:string[])

  • callbackDeps?: string[] CallbackDeps holds an array of state keys. When the value of the corresponding key in the state changes, the callback (network request, etc.) will be called.

Examples:

import { SyncQueryFactory, syncQueryCb } from "sync-query";

@SyncQueryFactory(['searchInput', 'pagination']) // Listen to searchInput or Pagination changes when synchronized to URL Query
export class MyComponent extends Component {

    @syncQueryCb(['searchInput']) // The fetch function is called to listen for a change in searchInput
    fetch() {
        // network fetch...
    }
}

Download Details:

Author: NeoYo

Source Code: https://github.com/NeoYo/sync-query

react reactjs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Increase Performance of React Applications Via Array JavaScript Methods

Increase Performance of React Applications Via Array JavaScript Methods. We will create a simple event management application in the react to add, update, and delete an event.

Routing in React without React-Router

I have been using React JS in my projects for quite some time now and am used to managing routing in my app using the react-router package. I have always been keen on having as little dependencies in my apps as possible, so, I always felt perturbed by the use of this particular package in simpler apps which did not have complex routes.

The Ugly Side of React Hooks

In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.

ReactJS: The Javascript Developer’s Guide

This article will walk you through the concepts you would need to know to step into the world of widely used ReactJS.