Socket
Socket
Sign inDemoInstall

react-router-use-location-state

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-router-use-location-state - npm Package Compare versions

Comparing version 2.2.0 to 2.3.0

dist/helpers/useRouter.d.ts

54

dist/react-router-use-location-state.cjs.js

@@ -5,3 +5,3 @@ 'use strict';

var useLocationState = require('use-location-state');
var useLocationState$1 = require('use-location-state');
var react = require('react');

@@ -36,3 +36,13 @@ var reactRouter = require('react-router');

function useReactRouterQueryStringInterface(history) {
function useRouter() {
return react.useContext(reactRouter.__RouterContext);
}
function useReactRouterQueryStringInterface() {
var router = useRouter();
var history = router && router.history;
if (!history) {
console.warn('useRouter - router was not found');
return;
}
return {

@@ -47,19 +57,37 @@ getQueryString: function () { return history.location.search; },

function useRouter() {
return react.useContext(reactRouter.__RouterContext);
function useQueryState(itemName, defaultValue, queryStateOpts) {
return useLocationState$1.useQueryState(itemName, defaultValue, __assign({ queryStringInterface: useReactRouterQueryStringInterface() }, queryStateOpts));
}
function useQueryState(itemName, defaultValue, queryStateOpts) {
function useReactRouterLocationStateInterface() {
var router = useRouter();
var queryStringInterface;
if (router && router.history) {
// eslint-disable-next-line react-hooks/rules-of-hooks
queryStringInterface = useReactRouterQueryStringInterface(router.history);
}
else {
var history = router && router.history;
if (!history) {
console.warn('useRouter - router was not found');
return;
}
return useLocationState.useQueryState(itemName, defaultValue, __assign({ queryStringInterface: queryStringInterface }, queryStateOpts));
return {
getLocationState: function () {
var historyState = history.location.state;
return ((historyState && useLocationState$1.LOCATION_STATE_KEY in historyState && historyState[useLocationState$1.LOCATION_STATE_KEY]) ||
{});
},
setLocationState: function (nextState, _a) {
var _b;
var _c = _a.method, method = _c === void 0 ? 'replace' : _c;
var historyState = history.location.state || {};
var updatedState = __assign(__assign({}, historyState), (_b = {}, _b[useLocationState$1.LOCATION_STATE_KEY] = nextState, _b));
// create current href, history re-routes incorrectly to "/" for ""
history[method](history.createHref(history.location), updatedState);
},
};
}
function useLocationState(itemName, defaultValue) {
return useLocationState$1.useLocationState(itemName, defaultValue, {
locationStateInterface: useReactRouterLocationStateInterface(),
});
}
exports.useLocationState = useLocationState;
exports.useQueryState = useQueryState;
exports.useRouter = useRouter;

@@ -1,3 +0,2 @@

import { QueryStateOpts, SetQueryStateItemFn } from 'use-location-state';
export declare function useRouter(): import("react-router").RouteComponentProps<{}, import("react-router").StaticContext, any>;
export declare function useQueryState<T>(itemName: string, defaultValue: T, queryStateOpts?: QueryStateOpts): [T, SetQueryStateItemFn<T>];
export { useQueryState } from './useQueryState/useQueryState';
export { useLocationState } from './useLocationState/useLocationState';

@@ -1,2 +0,2 @@

import { useQueryState as useQueryState$1 } from 'use-location-state';
import { useQueryState as useQueryState$1, LOCATION_STATE_KEY, useLocationState as useLocationState$1 } from 'use-location-state';
import { useContext } from 'react';

@@ -31,3 +31,13 @@ import { __RouterContext } from 'react-router';

function useReactRouterQueryStringInterface(history) {
function useRouter() {
return useContext(__RouterContext);
}
function useReactRouterQueryStringInterface() {
var router = useRouter();
var history = router && router.history;
if (!history) {
console.warn('useRouter - router was not found');
return;
}
return {

@@ -42,18 +52,36 @@ getQueryString: function () { return history.location.search; },

function useRouter() {
return useContext(__RouterContext);
function useQueryState(itemName, defaultValue, queryStateOpts) {
return useQueryState$1(itemName, defaultValue, __assign({ queryStringInterface: useReactRouterQueryStringInterface() }, queryStateOpts));
}
function useQueryState(itemName, defaultValue, queryStateOpts) {
function useReactRouterLocationStateInterface() {
var router = useRouter();
var queryStringInterface;
if (router && router.history) {
// eslint-disable-next-line react-hooks/rules-of-hooks
queryStringInterface = useReactRouterQueryStringInterface(router.history);
}
else {
var history = router && router.history;
if (!history) {
console.warn('useRouter - router was not found');
return;
}
return useQueryState$1(itemName, defaultValue, __assign({ queryStringInterface: queryStringInterface }, queryStateOpts));
return {
getLocationState: function () {
var historyState = history.location.state;
return ((historyState && LOCATION_STATE_KEY in historyState && historyState[LOCATION_STATE_KEY]) ||
{});
},
setLocationState: function (nextState, _a) {
var _b;
var _c = _a.method, method = _c === void 0 ? 'replace' : _c;
var historyState = history.location.state || {};
var updatedState = __assign(__assign({}, historyState), (_b = {}, _b[LOCATION_STATE_KEY] = nextState, _b));
// create current href, history re-routes incorrectly to "/" for ""
history[method](history.createHref(history.location), updatedState);
},
};
}
export { useQueryState, useRouter };
function useLocationState(itemName, defaultValue) {
return useLocationState$1(itemName, defaultValue, {
locationStateInterface: useReactRouterLocationStateInterface(),
});
}
export { useLocationState, useQueryState };

@@ -12,5 +12,5 @@ {

"dependencies": {
"use-location-state": "^2.2.0"
"use-location-state": "^2.3.0"
},
"version": "2.2.0",
"version": "2.3.0",
"author": "Felix Leupold <felix@xiel.de>",

@@ -36,3 +36,4 @@ "homepage": "https://github.com/xiel/use-location-state",

"scripts": {
"build": "rollup -c",
"cleanup": "rm -rf dist && rm -rf .rpt2_cache && rm -rf node_modules/.cache",
"build": "yarn cleanup; rollup -c",
"dev": "rollup -c -w",

@@ -47,3 +48,3 @@ "test": "echo \"Error: run tests from root\" && exit 1"

},
"gitHead": "bdcea17b02e683612f00d8f01e6f81fba17bcdc1"
"gitHead": "365b2ba5d13e32cb91a382356332330e3ab6e194"
}

@@ -1,2 +0,2 @@

# useQueryState()
<h1 style="width: 100%; text-align: center;"> { useLocationState, useQueryState }</h1>

@@ -10,3 +10,3 @@ [![npm (tag)](https://img.shields.io/npm/v/use-location-state/latest.svg)](https://www.npmjs.com/package/use-location-state)

store and retrieve state into/from the browsers location state using modern hooks
store and retrieve state into/from the browsers [location history](https://developer.mozilla.org/en-US/docs/Web/API/History) using modern hooks

@@ -16,6 +16,12 @@ ## ✨ Features

- makes it easy to provide a nice UX to your users, by restoring part of the app state after navigation actions
- makes it easy to share application in current state
- supported value types: `string | number | boolean | string[] | Date`
- handles stringification and parsing from query string of for supported value types
- invalid entries from the query string are discarded and the component will receive the defaultValue instead
- makes it easy to share the application in a customizable state
- __`useLocationState(name, defaultValue)`__
- restores the latest value after navigation actions (back/forward), by keeping value in `history.state`
- supported value types: `string | number | boolean | Date | Array | Object`
- handles complex & nested values - all values that can be serialized are supported
- __`useQueryState(name, defaultValue)`__
- restores the latest value from URL (`location.href`) and after navigation actions (back/forward)
- supported value types: `string | number | boolean | Date | string[]`
- handles stringification and parsing from query string of for supported value types
- invalid entries from the query string are discarded and the component will receive the defaultValue instead

@@ -28,14 +34,38 @@ ## Installation

Or install one of the optional [router integrations](#router-integration-optional)
Using __`react-router`__ or another popular router? For the best experience install one of the [router integrations](#router-integration-optional).
## Usage
The useQueryState() works similar to the `useState()` [hook](https://reactjs.org/docs/hooks-overview.html#state-hook) and returns the current value and a set function in a pair.
`useLocationState()` and `useQueryState()` work similar to the `useState()` [hook](https://reactjs.org/docs/hooks-overview.html#state-hook), as they also return the current value and a update function in a tuple `[currentValue, updateValueFn]`.
The *important difference* is that you need to pass a __name__ before your __default value__ for your state.
The *important difference* is that __you must pass a name__ before your __default value__ for your state.
```javascript
const [commentText, setCommentText] = useLocationState('commentText', '')
const [priceMax, setPriceMax] = useQueryState('priceMax', 30)
```
### useLocationState()
`useLocationState()` is perfect, when you want to store a state that should not be reflected in the URL or in case of a complex data structure like a nested object/array.
```javascript
const [commentText, setCommentText] = useLocationState('commentText', '')
```
The name you pass, in this case `'commentText'`, will be used as a key when storing the value. So when you use the same name in another component, you will get the same state.
```javascript
setCommentText('Wow, this works like a charm!')
```
The updated state will be restored when the pages reloads and after the user navigated to a new page and comes back using a back/forward action.
### useQueryState()
`useQueryState()` is a great, when you want to store information about the current state of you app in the URL.
```javascript
const [value, setValue] = useQueryState('itemName', 'default value')
```
The name you pass will be used in the query string store the state (after the state was changed).
The name you pass will be used as a parameter name in the query string, when setting a new value:

@@ -45,3 +75,3 @@ ```javascript

```
After calling the set function with a new value, the state will be saved withing the query string of the browser, so that the new state is reproducable after reloads or history navigation (using forward / back button).
After calling the update function `setValue()` with a new value, the state will be saved withing the query string of the browser, so that the new state is reproducable after reloads or history navigation (using forward / back button) or by loading the same URL anywhere else.

@@ -55,5 +85,5 @@ ```javascript

#### Push
### Push
In cases where you want the updated state to be represented as a new entry in the history, you can pass a options argument to the set function, with the method property set to `'push'`.
In cases where you want the updated state to be represented as a __new entry in the history__ you can pass a options object to the set function, with the method property set to `'push'`.

@@ -114,3 +144,3 @@ ```javascript

```javascript
import { useQueryState } from 'react-router-use-location-state'
import { useLocationState, useQueryState } from 'react-router-use-location-state'
```

@@ -128,1 +158,10 @@ Usage works the same as described above, except that the URL will look like this now:

Your favorite router is missing? Feel free to [suggest a router](https://github.com/xiel/use-location-state/issues).
## Compatibility
Tested in current versions Chrome, Firefox, Safari, Edge, and IE11. This library relies on new, yet stable ECMAScript features, so you might need to include a [polyfill](https://www.npmjs.com/package/react-app-polyfill#polyfilling-other-language-features) if you want to support older browsers like IE11:
```javascript
import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';
```
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc