Skip to content

Commit

Permalink
fix typo
Browse files Browse the repository at this point in the history
  • Loading branch information
drcmda committed Apr 9, 2019
0 parents commit 1315ab6
Show file tree
Hide file tree
Showing 9 changed files with 4,755 additions and 0 deletions.
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
node_modules/
coverage/
dist/
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
.DS_Store
.vscode
.docz/
package-lock.json
coverage/
.idea
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
examples/
21 changes: 21 additions & 0 deletions .size-snapshot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"dist/index.js": {
"bundled": 1518,
"minified": 567,
"gzipped": 351,
"treeshaked": {
"rollup": {
"code": 57,
"import_statements": 57
},
"webpack": {
"code": 1074
}
}
},
"dist/index.cjs.js": {
"bundled": 1949,
"minified": 816,
"gzipped": 406
}
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Paul Henschel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
44 changes: 44 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useState, useEffect } from 'react'

export default function create(fn) {
let listeners = []
let state = {
current: fn(
merge => {
if (typeof merge === 'function') {
merge = merge(state.current)
}
state.current = { ...state.current, ...merge }
listeners.forEach(listener => listener())
},
() => state.current
),
}
return (selector, dependencies) => {
const selected = selector(state.current)
// Using functional initial b/c selected itself could be a function
const [slice, set] = useState(() => selected)
useEffect(() => {
const ping = () => {
// Get fresh selected state
let selected = selector(state.current)
// If state is not a atomic shallow equal it
if (typeof selected === 'object' && !Array.isArray(selected)) {
selected = Object.entries(selected).reduce(
(acc, [key, value]) => (slice[key] !== value ? { ...acc, [key]: value } : acc),
slice
)
}
// Using functional initial b/c selected itself could be a function
if (slice !== selected) {
// Refresh local slice
set(() => selected)
}
}
listeners.push(ping)
return () => (listeners = listeners.filter(i => i !== ping))
}, dependencies || [selector])
// Returning the selected state slice
return selected
}
}
73 changes: 73 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{
"name": "msga",
"version": "0.0.0",
"description": "👍 Making React-state great again",
"main": "dist/index.cjs.js",
"module": "dist/index.js",
"sideEffects": false,
"scripts": {
"prebuild": "rimraf dist",
"build": "rollup -c",
"prepare": "npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"prettier": {
"semi": false,
"trailingComma": "es5",
"singleQuote": true,
"jsxBracketSameLine": true,
"tabWidth": 2,
"printWidth": 120
},
"lint-staged": {
"*.{js,}": [
"prettier --write",
"git add"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/drcmda/msga.git"
},
"keywords": [
"react",
"state",
"manager",
"management",
"redux",
"store"
],
"author": "Paul Henschel",
"license": "MIT",
"bugs": {
"url": "https://github.com/drcmda/msga/issues"
},
"homepage": "https://github.com/drcmda/msga#readme",
"dependencies": {
"@babel/runtime": "^7.4.3"
},
"devDependencies": {
"@babel/core": "7.3.4",
"@babel/plugin-transform-modules-commonjs": "7.2.0",
"@babel/plugin-transform-parameters": "7.3.3",
"@babel/plugin-transform-runtime": "7.3.4",
"@babel/plugin-transform-template-literals": "7.2.0",
"@babel/preset-env": "7.3.4",
"@babel/preset-react": "7.0.0",
"@babel/preset-typescript": "^7.3.3",
"husky": "^1.3.1",
"lint-staged": "^8.1.5",
"prettier": "^1.16.4",
"rimraf": "^2.6.3",
"rollup": "^1.9.0",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-node-resolve": "^4.2.1",
"rollup-plugin-size-snapshot": "^0.8.0",
"typescript": "^3.4.2"
}
}
121 changes: 121 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
npm install msga

React state is in a bit of a mess. Hundreds of solutions out there, the established options don't exactly go along well with hooks. There are dozens of solutions that claim you can replace, say, Redux with hooks and context, but most of them can't select state, so everything renders on every change, which IMO doesn't qualify as a state-manager.

#### Create a store (or multiple, up to you...)

```jsx
// Name your store anything you like, but remember, it's a hook!
const useStore = create(set => ({
// Everything in here is your state
count: 1,
// You don't have to nest your actions, but makes it easier to fetch them later on
actions: {
inc: () => set(state => ({ count: state.count + 1 })), // same semantics as setState
dec: () => set(state => ({ count: state.count - 1 })),
},
}))
```

#### Bind components

```jsx
function Counter() {
// Will only re-render the component when "count" changes
const count = useState(state => state.count)
return <h1>{count}</h1>
}

function Controlls() {
const { inc, dec } = useState(state => state.actions)
return (
<>
<button onClick={inc}>up</button>
<button onClick={down}>down</button>
</>
)
}
```

# Receipes

## Fetching everything

You can, but remember that it will cause the component to update on every state change!

```jsx
const data = useStore()
```

## Selecting multiple state slices

It's just like mapStateToProps in Redux. msga will run a small shallow euqal test over the object you return.

```jsx
const { name, age } = useStore(state => ({ name: state.name, age: state.age }))
```

## Fetching from multiple stores

You can create as many stores as you like, but you can also use data from one call in another.

```jsx
const currentUser = useCredentialsStore(state => state.currentUser)
const person = usePersonStore(state => state.persons[currentUser])
```

## Memoizing selectors (this is completely optional)

You can change the selector always. But additionally you can memoize it with an optional second argument that's similar to Reacts useMemo. You could do it without, but it will subscribe and unsubscribe to the store on every render pass. Not that big of a deal, unless you're dealing with thousands of connected components.

```jsx
const book = useBookStore(state => state.books[title], [title])
```

## Async actions

Just call `set` when you're ready, it doesn't care if your actions are async or not.

```jsx
const useStore = create(set => ({
result: '',
fetch: async url => {
const response = await fetch(url)
const json = await response.json()
set({ result: json })
},
}))
```

## Read from state in actions

The `set` function already allows functional update `set(state => result)` but should there be cases where you need to access outside of it you have an optional `get`, too.

```jsx
const useStore = create((set, get) => ({
text: "hello",
action: () => {
const text = get().text
///...
}
})
```
## Sick of reducers and changing nested state? Use Immer!
```jsx
import produce from "immer"

const useStore = create((set, get) => ({
nested: {
structure: {
constains: {
a: "value"
}
}
},
action: () => set(produce(draft => {
draft.nested.structure.contains.a.value = undefined // not anymore ...
}))
})
```
43 changes: 43 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import path from 'path'
import babel from 'rollup-plugin-babel'
import resolve from 'rollup-plugin-node-resolve'
import { sizeSnapshot } from 'rollup-plugin-size-snapshot'

const root = process.platform === 'win32' ? path.resolve('/') : '/'
const external = id => !id.startsWith('.') && !id.startsWith(root)
const extensions = ['.js', '.jsx', '.ts', '.tsx']
const getBabelOptions = ({ useESModules }, targets) => ({
babelrc: false,
extensions,
exclude: '**/node_modules/**',
runtimeHelpers: true,
presets: [
['@babel/preset-env', { loose: true, modules: false, targets }],
'@babel/preset-react',
'@babel/preset-typescript',
],
plugins: [['@babel/transform-runtime', { regenerator: false, useESModules }]],
})

function createConfig(entry, out) {
return [
{
input: entry,
output: { file: `dist/${out}.js`, format: 'esm' },
external,
plugins: [
babel(getBabelOptions({ useESModules: true }, '>1%, not dead, not ie 11, not op_mini all')),
sizeSnapshot(),
resolve({ extensions }),
],
},
{
input: entry,
output: { file: `dist/${out}.cjs.js`, format: 'cjs' },
external,
plugins: [babel(getBabelOptions({ useESModules: false })), sizeSnapshot(), resolve({ extensions })],
},
]
}

export default [...createConfig('index', 'index')]
Loading

0 comments on commit 1315ab6

Please sign in to comment.