state-as-querystring
v1.2.0
Published
Save application state in the querystring. Restore it when page is refreshed.
Downloads
8
Maintainers
Readme
state-as-querystring
Save your application state in query string between page views.
String, Number and Boolean and Array values will be saved as is, while object values will be encoded as JSON.
Usage
Idea is simple. When state in initiated, we read it from the query string. Whenever it changes, we write it to the query string. This keeps start between page views and allows sharing urls of a given state.
React example
import { saveStateToURL, readStateFromURL } from "state-as-querystring";
class App extends React.Component {
// read state from url when initializing the store
constructor(props) {
super(props);
this.state = readStateFromURL();
}
//save state to url when state is changed
componentDidUpdate() {
saveStateToURL(this.state);
}
render() {
return (
<textarea
value={this.state.text}
/>
);
}
}
Redux example
import { saveStateToURL, readStateFromURL } from "state-as-querystring";
// read state from url when initializing the store
const store = createStore(reducer, readStateFromURL());
// save state to url when state changes
store.subscribe(() => saveStateToURL(store.getState()));
A bit more complex example - with arrays in the state + partial syncing of the state.