Skip to content

Commit

Permalink
Trial an initial loader from DOM
Browse files Browse the repository at this point in the history
  • Loading branch information
ultraq committed May 26, 2020
1 parent 42b96ff commit ef3e4c8
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"env": {
"browser": true
}
}
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ultraq/redux-utils",
"version": "0.2.0",
"version": "0.3.0",
"description": "A collection of wrappers/utilities for common functions in redux",
"author": "Emanuel Rabina <emanuelrabina@gmail.com> (http://www.ultraq.net.nz/)",
"license": "Apache-2.0",
Expand Down
27 changes: 27 additions & 0 deletions redux-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,33 @@

import {equals} from '@ultraq/object-utils';

/**
* Create an initial state from JSON data in a DOM element. Used for creating
* an object that is suitable for the `initialState` value of Redux's
* `createStore`.
*
* @param {String} selector
* A CSS selector for picking out the HTML element that contains the JSON data
* to load.
* @param {String} [slice]
* If the JSON data only represents a slice of the entire state, then specify
* the name of the slice so that it can be set in the right place.
* @return {Object}
* The JSON data converted to an object, or an empty object if no data could
* be read.
*/
export function initialStateFromDom(selector, slice) {
let el = document.querySelector(selector);
if (el && el.textContent) {
let jsonData = el.textContent.trim();
if (jsonData) {
let data = JSON.parse(jsonData);
return slice ? {[slice]: data} : data;
}
}
return {};
}

/**
* Observe the store for changes, passing the value picked out by the `select`
* function to the handler.
Expand Down

0 comments on commit ef3e4c8

Please sign in to comment.