• This repository has been archived on 12/Jan/2023
  • Stars
    star
    118
  • Rank 294,983 (Top 6 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Utilities for reading & writing Redux store state to & from the URL

Build Status

redux-location-state

Utilities for reading & writing Redux store state to & from the URL. For use cases and reasoning about why this package exists, please read the blog post: https://labs.spotify.com/2017/08/10/thinking-of-state-in-a-world-of-urls/

Development Status

2.0 is updated for release of React Router V4

How it works

setup before compose

The basic idea is that you pass a config object and based on when the state gets updated, certain query params will follow along, and if a user goes back or forward the state gets updated based on query params. For example

{
  p: {stateKey: 'foo', initialState: 'bazz', options: {shouldPush: true}},
}

will make a query param of p equal to the state that is passed in with the value on foo

config

First you need to create a config object

const paramSetup = {
    '/': {
      p: {stateKey: 'foo', initialState: 'bazz', options: {shouldPush: true}},
      s: {stateKey: 'bar', initialState: {}, options: {isFlags: true}},
    },
    global: {
      split: {stateKey: 'baz'},
    }
  };

Each page that you have declared should have an object of what to track, since you most likely don't want to track all of your state in the url this is helpful to pair down what you need

Each key should be the path. If you have a variable path you can add /* to show that it is a variable

Additionally, if you would like to track state no matter which page you're on, create an object with a key of global.

The idea is that you declare the name you would like the url param to be, and then declare where that state lives in your state object for redux-location-state to map.

mapLocationToState

Redux-location-state relies on redux reducers to update the state if the url changes. For this Parameter, pass in a reducer that you would use to parse the returned data

//location is a React location object with the query object updated with the mapped values
function mapLocationToState(state, location) {
  switch (location.pathname) {
    case "/":
      const queryState = location.query;

      //notice that it maps the query back to the stateKey
      state.foo = queryState.foo;
      state.bar = queryState.bar;
      return state;

    default:
      return state;
  }
}

history

this will be react-router's hashHistory or browserHistory

reducer

Redux-location-state relies on redux reducers to update the state if the url changes. if you already have other reducers that you've made, you can simply pass them in below and it will return a new function with all your previous reducers as well as a new location reducer attached.

initialization

import {createStore, applyMiddleware, compose} from 'redux';
import {Router} from 'react-router-dom';
import {createReduxLocationActions, listenForHistoryChange} from 'redux-location-state';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

const {locationMiddleware, reducersWithLocation} = createReduxLocationActions(paramSetup, mapLocationToState, history, reducers);
const store = compose(applyMiddleware([locationMiddleware]))(createStore)(reducersWithLocation);

you have now initialized your store with the location. Now all you have to do is start watching the url changes.

listenForHistoryChange(store, history);

you have now turned on your location watcher!

options

There are a lot of options that you have available in your config object.

For every type of item there is a couple of default options that you can pass.

type

If your redux store value is anything other than a string, it will need to be defined in the type key

{
  s: {stateKey: 'bar', type: 'object'},
  r: {stateKey: 'foo', type: 'date'},
  q: {stateKey: 'biz', type: 'number'},
  i: {stateKey: 'biz', type: 'array'},
  w: {stateKey: 'tan', type: 'bool'},
}

initialState

This is declared on the top most level and will tell redux-location-state what the default is. If it is not declared it will assume undefined is the default.

{
  s: {stateKey: 'bar', initialState: {}},
}

serialize

If you'd like to control how your item is shown in the url, you can pass in a function on options.serialize, which expects a string ready to be put on the url

p: {stateKey: 'foo', options: {
  serialize: (currentItemState) => {
    return currentItemState.join('I-like-to-join-by-hyphens-and-words');
  }
}}

parse

Converse to serialize, if you pass this function in your config you can set your store however you'd like

p: {stateKey: 'foo', options: {
  parse: (urlPathReturned) => {
    return urlPathReturned.split('I-like-to-join-by-hyphens-and-words');
  }
}}

shouldPush

By default, if there is a query param update it will only replace the url (it won't be added to your history), you can override it by adding shouldPush to your options

p: {stateKey: 'foo', options: {shouldPush: true}}

delimiter

This only applies to arrays and objects, but you can declare how you'd like to delimit your items. by default it is -, but it can be overwritten

p: {stateKey: 'foo', options: {delimiter: '_'}

setAsEmptyItem

Another item that only applies to arrays or objects. if you've declared an empty object or array as the default, it will assume if it sees nothing in the query param that you want undefined. you can explicitly tell it to return an empty array or object by passing this flag as true.

array

In addition, there are some array specific options

keepOrder

If you have an ordered array that you'd like to keep the order in the url, pass keepOrder as true

object

isFlags

For objects, you have the ability to pass in an object that just has true/false values. by passing the isFlags boolean, it will serialize only the items that are true and inline them

if the config is

{
  p: {stateKey: 'foo', defaultValue: {}, type: 'object', options: {isFlags: true, }},
}

and the state is

{
  '/': {
    foo: {
      bazz: true,
      bar: false,
      bin: true,
    }
  }
}

the url will be ?p=bazz-bin

experimental

If you'd like to parse all the objects in a custom way, you can add a fifth argument to createReduxLocationActions that will overwrite the function that maps the query params. this function will have to return a location object with the updated params in the query object.

function overwriteLocationHandling(setupObject, nextState, location) {
  location.query.something = nextState;
  return location;
}

Overwrite accessors

Some libraries (like immutable.js) won't allow you to use lodash's get function. There is an escape hatch to import your own get, set, or isEqual. You'll need to add a RLSCONFIG key with an object to your setup config.

{
  RLSCONFIG: {
    'overwrite-accessors': {
      get: immutableGet,
      set: immutableSet,
      isEqual: immutableIsEqual
    }
  }
}

Overwrite query parser

By default, the parser for query params will split on =, however, this doesn't take into account that there may be other = in the query param value. There also may need to be other ways to split query parameters, so you can now also pass in your own custom query param parser, like so:

{
  RLSCONFIG: {
    queryParser: (q) => (q.split('='))
  }
}

Development

To work on the project, run an npm install then run the following commands for different uses:

  • npm run serve to check localhost 8000 and see an example
  • npm run build to build src into lib and run tests

Code of Conduct

This project adheres to the Open Code of Conduct. By participating, you are expected to honor this code.

More Repositories

1

luigi

Luigi is a Python module that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization etc. It also comes with Hadoop support built in.
Python
17,581
star
2

annoy

Approximate Nearest Neighbors in C++/Python optimized for memory usage and loading/saving to disk
C++
12,950
star
3

docker-gc

INACTIVE: Docker garbage collection of containers and images
Shell
5,068
star
4

pedalboard

🎛 🔊 A Python library for audio.
C++
4,964
star
5

chartify

Python library that makes it easy for data scientists to create charts.
Python
3,486
star
6

basic-pitch

A lightweight yet powerful audio-to-MIDI converter with pitch bend detection
Python
2,972
star
7

dockerfile-maven

MATURE: A set of Maven tools for dealing with Dockerfiles
Java
2,748
star
8

docker-maven-plugin

INACTIVE: A maven plugin for Docker
Java
2,652
star
9

scio

A Scala API for Apache Beam and Google Cloud Dataflow.
Scala
2,485
star
10

helios

Docker container orchestration platform
Java
2,097
star
11

web-api-examples

Basic examples to authenticate and fetch data using the Spotify Web API
HTML
1,889
star
12

HubFramework

DEPRECATED – Spotify’s component-driven UI framework for iOS
Objective-C
1,863
star
13

apollo

Java libraries for writing composable microservices
Java
1,648
star
14

dh-virtualenv

Python virtualenvs in Debian packages
Python
1,601
star
15

docker-client

INACTIVE: A simple docker client for the JVM
Java
1,429
star
16

docker-kafka

Kafka (and Zookeeper) in Docker
Shell
1,400
star
17

SPTPersistentCache

Everyone tries to implement a cache at some point in their iOS app’s lifecycle, and this is ours.
Objective-C
1,243
star
18

mobius

A functional reactive framework for managing state evolution and side-effects.
Java
1,213
star
19

voyager

🛰️ An approximate nearest-neighbor search library for Python and Java with a focus on ease of use, simplicity, and deployability.
C++
1,175
star
20

sparkey

Simple constant key/value storage library, for read-heavy systems with infrequent large bulk inserts.
C
1,153
star
21

ruler

Gradle plugin which helps you analyze the size of your Android apps.
Kotlin
1,118
star
22

XCMetrics

XCMetrics is the easiest way to collect Xcode build metrics and improve developer productivity.
Swift
1,095
star
23

web-api

This issue tracker is no longer used. Join us in the Spotify for Developers forum for support with the Spotify Web API ➡️ https://community.spotify.com/t5/Spotify-for-Developers/bd-p/Spotify_Developer
RAML
981
star
24

echoprint-codegen

Codegen for Echoprint
C++
948
star
25

snakebite

A pure python HDFS client
Python
858
star
26

heroic

The Heroic Time Series Database
Java
843
star
27

klio

Smarter data pipelines for audio.
Python
832
star
28

XCRemoteCache

Swift
824
star
29

SPTDataLoader

The HTTP library used by the Spotify iOS client
Objective-C
629
star
30

ios-sdk

Spotify SDK for iOS
Objective-C
627
star
31

apps-tutorial

A Spotify App that contains working examples of the use of Spotify Apps API
627
star
32

JniHelpers

Tools for writing great JNI code
C++
590
star
33

postgresql-metrics

Tool that extracts and provides metrics on your PostgreSQL database
Python
589
star
34

Mobius.swift

A functional reactive framework for managing state evolution and side-effects [Swift implementation]
Swift
556
star
35

reactochart

📈 React chart component library 📉
JavaScript
551
star
36

dockerfile-mode

An emacs mode for handling Dockerfiles
Emacs Lisp
529
star
37

threaddump-analyzer

A JVM threaddump analyzer
JavaScript
486
star
38

featran

A Scala feature transformation library for data science and machine learning
Scala
465
star
39

android-sdk

Spotify SDK for Android
HTML
449
star
40

echoprint-server

Server for the Echoprint audio fingerprint system
Java
396
star
41

completable-futures

Utilities for working with futures in Java 8
Java
385
star
42

web-scripts

DEPRECATED: A collection of base configs and CLI wrappers used to speed up development @ Spotify.
TypeScript
381
star
43

SpotifyLogin

Swift framework for authenticating with the Spotify API
Swift
346
star
44

ratatool

A tool for data sampling, data generation, and data diffing
Scala
337
star
45

spotify-web-api-ts-sdk

A Typescript SDK for the Spotify Web API with types for returned data.
TypeScript
312
star
46

fmt-maven-plugin

Opinionated Maven Plugin that formats your Java code.
Java
309
star
47

big-data-rosetta-code

Code snippets for solving common big data problems in various platforms. Inspired by Rosetta Code
Scala
287
star
48

trickle

A small library for composing asynchronous code
Java
284
star
49

pythonflow

🐍 Dataflow programming for python.
Python
283
star
50

coordinator

A visual interface for turning an SVG into XY coördinates.
HTML
283
star
51

styx

"The path to execution", Styx is a service that schedules batch data processing jobs in Docker containers on Kubernetes.
Java
266
star
52

cstar

Apache Cassandra cluster orchestration tool for the command line
Python
255
star
53

netty-zmtp

A Netty implementation of ZMTP, the ZeroMQ Message Transport Protocol.
Java
242
star
54

ios-style

Guidelines for iOS development in use at Spotify
241
star
55

confidence

Python
238
star
56

cassandra-reaper

Software to run automated repairs of cassandra
235
star
57

docker-cassandra

Cassandra in Docker with fast startup
Shell
220
star
58

terraform-gke-kubeflow-cluster

Terraform module for creating GKE clusters to run Kubeflow
HCL
209
star
59

linux

Spotify's Linux kernel for Debian-based systems
C
206
star
60

basic-pitch-ts

A lightweight yet powerful audio-to-MIDI converter with pitch bend detection.
TypeScript
206
star
61

dns-java

DNS wrapper library that provides SRV lookup functionality
Java
204
star
62

git-test

test your commits
Shell
202
star
63

SPStackedNav

[DEPRECATED] Navigation controller which represents its content in stacks of panes, rather than one at a time
Objective-C
195
star
64

spotify-json

Fast and nice to use C++ JSON library.
C++
194
star
65

quickstart

A CommonJS module resolver, loader and compiler for node.js and browsers.
JavaScript
193
star
66

dbeam

DBeam exports SQL tables into Avro files using JDBC and Apache Beam
Java
188
star
67

flink-on-k8s-operator

Kubernetes operator for managing the lifecycle of Apache Flink and Beam applications.
Go
180
star
68

bazel-tools

Tools for dealing with very large Bazel-managed repositories
Java
165
star
69

lingon

A user friendly tool for building single-page JavaScript applications
JavaScript
162
star
70

dataenum

Algebraic data types in Java.
Java
161
star
71

magnolify

A collection of Magnolia add-on modules
Scala
158
star
72

async-google-pubsub-client

[SUNSET] Async Google Pubsub Client
Java
157
star
73

gcp-audit

A tool for auditing security properties of GCP projects.
Python
156
star
74

spark-bigquery

Google BigQuery support for Spark, SQL, and DataFrames
Scala
155
star
75

should-up

Remove most of the "should" noise from your tests
JavaScript
150
star
76

folsom

An asynchronous memcache client for Java
Java
146
star
77

flo

A lightweight workflow definition library
Java
146
star
78

missinglink

Build time tool for detecting link problems in java projects
Java
143
star
79

android-auth

Spotify authentication and authorization for Android. Part of the Spotify Android SDK.
HTML
140
star
80

proto-registry

An implementation of the Protobuf Registry API
TypeScript
140
star
81

zoltar

Common library for serving TensorFlow, XGBoost and scikit-learn models in production.
Java
138
star
82

futures-extra

Java library for working with Guava futures
Java
136
star
83

annoy-java

Approximate nearest neighbors in Java
Java
136
star
84

spydra

Ephemeral Hadoop clusters using Google Compute Platform
Java
134
star
85

spotify-web-playback-sdk-example

React based example app that creates a new player in Spotify Connect to play music from in the browse using Spotify Web Playback SDK.
JavaScript
134
star
86

docker-stress

Simple docker stress test and monitoring tools
Python
125
star
87

spotify-tensorflow

Provides Spotify-specific TensorFlow helpers
Python
124
star
88

crtauth

a public key backed client/server authentication system
Python
118
star
89

sparkey-java

Java implementation of the Sparkey key value store
Java
117
star
90

github-java-client

A Java client to Github API
Java
114
star
91

realbook

Easier audio-based machine learning with TensorFlow.
Python
109
star
92

rspec-dns

Easily test your DNS with RSpec
Ruby
107
star
93

web-playback-sdk

This issue tracker is no longer used. Join us in the Spotify for Developers forum for support with the Spotify Web Playback SDK ➡️ https://community.spotify.com/t5/Spotify-for-Developers/bd-p/Spotify_Developer
107
star
94

ffwd-ruby

An event and metrics fast-forwarding agent.
Ruby
105
star
95

gimme

Creating time bound IAM Conditions with ease and flair
Python
103
star
96

super-smash-brogp

Sends and withdraws BGP prefixes for fun.
Python
98
star
97

lighthouse-audit-service

TypeScript
94
star
98

python-graphwalker

Python re-implementation of the graphwalker testing tool
Python
93
star
99

noether

Scala Aggregators used for ML Model metrics monitoring
Scala
91
star
100

spotify.github.io

Showcase site for hand-picked open-source projects by Spotify
HTML
88
star