1

In my redux app I have some settings that should be persisted to disk when they change (as JSON file) and loaded with the app (to fill the initial state of the store).

I guess app settings are state, so they belong in the store. Then I have actions that modify settings, either like SETTINGS/CHANGE with payload {name:'settingName', value: 'settingvalue'} or fine grained like SETTINGS/UNITS with payload 'metric' or 'imperial'.

Now I need something that intercepts certain state changes/action submissions and persist them to disk as serialized JSON. Is this something the settings reducer should do itself or better some kind of middleware that can perform this async in the background?

How would that look like in code?

philk
  • 2,009
  • 1
  • 23
  • 36
  • 2
    There is the https://github.com/michaelcontento/redux-storage middleware you could take a look at, it does the same but for localStorage. – krs Feb 03 '16 at 02:43
  • Looks exactly like I was looking for. Will give it a try – philk Feb 03 '16 at 07:42
  • Possible duplicate of [Where to write to localStorage in a Redux app?](http://stackoverflow.com/questions/35305661/where-to-write-to-localstorage-in-a-redux-app) – Dan Abramov Feb 27 '16 at 22:09

1 Answers1

1

You may use localStorage API as krs said. Care because it only allows string values, so you may need to stringify your objects before storing them:

var config = {
    foo: 'foo',
    bar: 'bar'
}

// Store:
localStorage.setItem('config', JSON.stringify(config));

// Get
JSON.parse(localStorage.getItem('config'));
martpie
  • 5,510
  • 1
  • 21
  • 25