{"id":24838557,"url":"https://github.com/suren-atoyan/state-local","last_synced_at":"2025-05-12T14:51:26.366Z","repository":{"id":56310676,"uuid":"285533843","full_name":"suren-atoyan/state-local","owner":"suren-atoyan","description":"⚡ Tiny, simple, and robust technique for defining and acting with local states","archived":false,"fork":false,"pushed_at":"2024-05-02T15:09:32.000Z","size":181,"stargazers_count":23,"open_issues_count":0,"forks_count":4,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-29T06:03:56.314Z","etag":null,"topics":["javascript","state","state-management"],"latest_commit_sha":null,"homepage":"https://github.com/suren-atoyan/local-state","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/suren-atoyan.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-06T09:49:28.000Z","updated_at":"2024-12-14T15:05:16.000Z","dependencies_parsed_at":"2024-06-18T15:32:57.890Z","dependency_job_id":"3dfdef47-97d7-470d-8a42-fd55e91b7036","html_url":"https://github.com/suren-atoyan/state-local","commit_stats":{"total_commits":34,"total_committers":4,"mean_commits":8.5,"dds":0.08823529411764708,"last_synced_commit":"d72a69c6cbb133eead0797446e4954a92d114b8e"},"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/suren-atoyan%2Fstate-local","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/suren-atoyan%2Fstate-local/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/suren-atoyan%2Fstate-local/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/suren-atoyan%2Fstate-local/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/suren-atoyan","download_url":"https://codeload.github.com/suren-atoyan/state-local/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253758843,"owners_count":21959660,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","state","state-management"],"created_at":"2025-01-31T06:20:54.737Z","updated_at":"2025-05-12T14:51:26.313Z","avatar_url":"https://github.com/suren-atoyan.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# State \u0026middot; [![monthly downloads](https://img.shields.io/npm/dm/state-local)](https://www.npmjs.com/package/state-local) [![gitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/suren-atoyan/state-local/blob/master/LICENSE) [![Rate on Openbase](https://badges.openbase.io/js/rating/state-local.svg)](https://openbase.io/js/state-local?utm_source=embedded\u0026utm_medium=badge\u0026utm_campaign=rate-badge) [![build size](https://img.shields.io/bundlephobia/minzip/state-local)](https://bundlephobia.com/result?p=state-local) [![npm version](https://img.shields.io/npm/v/state-local.svg?style=flat)](https://www.npmjs.com/package/state-local)  [![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/suren-atoyan/state-local/pulls)\n\n:zap: Tiny, simple, and robust technique for defining and acting with local states (for all js environments - node, browser, etc.)\n\n## Synopsis\n\nA local state for modules, functions, and other ECs\n\n## Motivation\n\nWe all love functional programming and the concepts of it. It gives us many clean patterns, which we use in our code regardless of exactly which paradigm is in the base of our codebase. But sometimes, for some reason, we can't keep our code \"clean\" and have to interact with items that are outside of the current lexical environment\n\nFor example:\n\n:x:\n```javascript\nlet x = 0;\nlet y = 1;\n\n// ...\nfunction someFn() {\n  // ...\n  x++;\n}\n\n// ...\nfunction anotherFn() {\n // ...\n y = 6;\n console.log(x);\n}\n\n// ...\nfunction yetAnotherFn() {\n  // ...\n  y = x + 4;\n  x = null; // 🚶\n}\n```\n\nThe example above lacks control over the mutations and consumption, which can lead to unpredictable and unwanted results. It is just an example of real-life usage and there are many similar cases that belong to the same class of the problem\n\n**The purpose of this library is to give an opportunity to work with local states in a clear, predictable, trackable, and strict way**\n\n:white_check_mark:\n\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ x: 0, y: 1 });\n\n// ...\nfunction someFn() {\n  // ...\n  setState(state =\u003e ({ x: state.x + 1 }));\n}\n\n// ...\nfunction anotherFn() {\n // ...\n setState({ y: 6 });\n const state = getState();\n console.log(state);\n}\n\n// ...\nfunction yetAnotherFn() {\n  // ...\n  setState(state =\u003e ({ y: state.x + 4, x: null }));\n}\n```\n\n[codesandbox](https://codesandbox.io/s/motivation-1-xv5el?file=/src/index.js)\n\nWe also can track the changes in items:\n\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ x: 0, y: 1 }, {\n  x: latestX =\u003e console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; \"x\" has been changed. \"x\" now is:', latestX),\n  y: latestY =\u003e console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; \"y\" has been changed. \"y\" now is:', latestY),\n});\n\n// ...\n```\n\n[codesandbox](https://codesandbox.io/s/motivation-2-ivf7d)\n\nWe can use the subset of the state in some execution contexts:\n\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ x: 5, y: 7 });\n\n// ...\nfunction someFn() {\n  const state = getState(({ x }) =\u003e ({ x }));\n\n  console.log(state.x); // 5\n  console.log(state.y); // ❌ undefined - there is no y\n}\n```\n\n[codesandbox](https://codesandbox.io/s/motivation-3-femne)\n\nAnd much more...\n\n## Documentation\n\n#### Contents\n\n* [Installation](#installation)\n* Usage\n  * [create](#create)\n  * [initial state](#initial-state)\n  * [handler](#handler)\n  * [getState](#getstate)\n  * [selector](#selector)\n  * [setState](#setstate)\n\n#### Installation\n\nYou can install this library as an npm package or download it from the CDN and use it in node or browser:\n\n```bash\nnpm install state-local\n```\nor\n```bash\nyarn add state-local\n```\n\nor\n\n```html\n\u003cscript src=\"https://unpkg.com/state-local/dist/state-local.js\"\u003e\u003c/script\u003e\n\n\u003cscript\u003e\n// now it is available in `window` (window.state)\nconst [getState, setState] = state.create({ x: 11, y: 13 });\n// ...\n\u003c/script\u003e\n```\n\n#### create\n\nThe default export has a method called `create`, which is supposed to be a function to create a state:\n\n```javascript\nimport state from 'state-local';\n\n// state.create\n\n// ...\n```\n\n[codesandbox](https://codesandbox.io/s/docs-create-t1cxe)\n\n`create` is a function with two parameters:\n\n1) [`initial state`](#initial-state) (**required**)\n2) [`handler`](#handler) (**optional**)\n\n#### initial state\n\n`initial state` is a base structure and a value for the state. It should be a non-empty object\n\n```javascript\nimport state from 'state-local';\n\n/*\nconst [getState, setState] = state.create(); // ❌ error - initial state is required\nconst [getState, setState] = state.create(5); // ❌ error - initial state should be an object\nconst [getState, setState] = state.create({}); // ❌ error - initial state shouldn\\'t be an empty object\n*/\n\nconst [getState, setState] = state.create({ isLoading: false, payload: null }); // ✅\n// ...\n```\n\n[codesandbox](https://codesandbox.io/s/docs-initial-state-22i3s)\n\n#### handler\n\n`handler` is a second parameter for `create` function and it is optional. It is going to be a handler for state updates. Hence it can be either a function or an object.\n\n- If the handler is a function than it should be called immediately after every state update (with the latest state)\n- If the handler is an object than the keys of that object should be a subset of the state and the values should be called immediately after every update of the corresponding field in the state (with the latest value of the field)\n\nsee example below:\n\nif `handler` is a function\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ x: 2, y: 3, z: 5 }, handleStateUpdate /* will be called immediately after every state update */);\n\nfunction handleStateUpdate(latestState) {\n  console.log('hey state has been updated; the new state is:', latestState); // { x: 7, y: 11, z: 13 }\n}\n\nsetState({ x: 7, y: 11, z: 13 });\n// ...\n```\n\n[codesandbox](https://codesandbox.io/s/handler-function-uevxj)\n\nif `handler` is an object\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ x: 2, y: 3, z: 5 }, {\n  x: handleXUpdate, // will be called immediately after every \"x\" update\n  y: handleYUpdate, // will be called immediately after every \"y\" update\n  // and we don't want to listen \"z\" updates 😔\n});\n\nfunction handleXUpdate(latestX) {\n  console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; \"x\" has been changed. \"x\" now is:', latestX); // ... \"x\" now is 7\n}\n\nfunction handleYUpdate(latestY) {\n  console.log('(⌐▀ ̯ʖ▀) Houston we have a problem; \"y\" has been changed. \"y\" now is:', latestY); // ... \"y\" now is 11\n}\n\nsetState({ x: 7, y: 11, z: 13 });\n// ...\n```\n\n[codesandbox](https://codesandbox.io/s/handler-object-8k0pt)\n\n#### getState\n\n`getState` is the first element of the pair returned by `create` function. It will return the current state or the subset of the current state depending on how it was called. It has an optional parameter `selector`\n\n```javascript\nimport state from \"state-local\";\n\nconst [getState, setState] = state.create({ p1: 509, p2: 521 });\n\nconst state = getState();\nconsole.log(state.p1); // 509\nconsole.log(state.p2); // 521\n\n// or\n\nconst { p1, p2 } = getState();\nconsole.log(p1); // 509\nconsole.log(p2); // 521\n```\n\n[codesandbox](https://codesandbox.io/s/getstate-zn3hj)\n\n#### selector\n\n`selector` is a function that is supposed to be passed (optional) as an argument to `getState`. It receives the current state and returns a subset of the state\n\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ p1: 389, p2: 397, p3: 401 });\n\nfunction someFn() {\n  const state = getState(({ p1, p2 }) =\u003e ({ p1, p2 }));\n  console.log(state.p1); // 389\n  console.log(state.p2); // 397\n  console.log(state.p3); // ❌ undefined - there is no p3\n}\n```\n\n[codesandbox](https://codesandbox.io/s/selector-vjmdu)\n\n#### setState\n\n`setState` is the second element of the pair returned by `create` function. It is going to receive an object as a change for the state. The change object will be shallow merged with the current state and the result will be the next state\n\n**NOTE: the change object can't contain a field that is not specified in the \"initial\" state**\n\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ x:0, y: 0 });\n\nsetState({ z: 'some value' }); // ❌ error - it seams you want to change a field in the state which is not specified in the \"initial\" state\n\nsetState({ x: 11 }); // ✅ ok\nsetState({ y: 1 }); // ✅ ok\nsetState({ x: -11, y: 11 }); // ✅ ok\n```\n\n[codesandbox](https://codesandbox.io/s/setstate-1-u4fq0)\n\n`setState` also can receive a function which will be called with the current state and it is supposed to return the change object\n\n```javascript\nimport state from 'state-local';\n\nconst [getState, setState] = state.create({ x:0, y: 0 });\n\nsetState(state =\u003e ({ x: state.x + 2 })); // ✅ ok\nsetState(state =\u003e ({ x: state.x - 11, y: state.y + 11 })); // ✅ ok\n\nsetState(state =\u003e ({ z: 'some value' })); // ❌ error - it seams you want to change a field in the state which is not specified in the \"initial\" state\n```\n\n[codesandbox](https://codesandbox.io/s/smoosh-wildflower-nv9dg)\n\n## License\n\n[MIT](./LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsuren-atoyan%2Fstate-local","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsuren-atoyan%2Fstate-local","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsuren-atoyan%2Fstate-local/lists"}