Skip to content

Commit 8915eb2

Browse files
committed
Fix bug where we attach/detach on every render. + Documentation + ESLint config
1 parent 5d90a3b commit 8915eb2

File tree

5 files changed

+1289
-13
lines changed

5 files changed

+1289
-13
lines changed

.eslintrc.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
module.exports = {
2+
env: {
3+
browser: true,
4+
es6: true,
5+
node: true,
6+
},
7+
extends: 'airbnb',
8+
globals: {
9+
Atomics: 'readonly',
10+
SharedArrayBuffer: 'readonly',
11+
},
12+
parserOptions: {
13+
ecmaFeatures: {
14+
jsx: true,
15+
},
16+
ecmaVersion: 2018,
17+
sourceType: 'module',
18+
},
19+
plugins: [
20+
'react',
21+
],
22+
rules: {
23+
},
24+
};

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

index.js

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
11
import { useEffect, useReducer } from 'react';
22

3+
// useFluxStore essentially combines useReducer and useEffect to use with FluxStores
4+
// useReducer: Used to extract relevant values from the store
5+
// useEffect is used to attach a listener to the store
6+
37
export function useFluxStore(store, storeReducer) {
4-
const [out, _dispatch] = useReducer((prevState, store) => {
5-
return storeReducer(prevState, store)
6-
}, storeReducer(null, store))
8+
// Call useReducer and set initial value from current state of store.
9+
const [out, _dispatch] = useReducer(storeReducer, storeReducer(null, store));
710

811
useEffect(() => {
912
function listener() {
10-
_dispatch(store)
13+
// When store is updated, we dispatch an update to the reducer
14+
_dispatch(store);
1115
}
1216

13-
const token = store.addListener(listener)
14-
return () => {
15-
token.remove()
16-
}
17-
})
18-
return out
17+
// Attach reducer's listener to store
18+
const token = store.addListener(listener);
19+
// On useEffect destruction, remove the listener
20+
return () => token.remove();
21+
},
22+
[]); // We make sure to pass [] so we're not attaching/detaching on every render
23+
return out; // Reducer value gets returned to useFluxStore
1924
}
2025

21-
export default useFluxStore
26+
export default useFluxStore;

package.json

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,12 @@
2323
"bugs": {
2424
"url": "https://github.com/Fieldscope/flux-hooks/issues"
2525
},
26-
"homepage": "https://github.com/Fieldscope/flux-hooks#readme"
27-
}
26+
"homepage": "https://github.com/Fieldscope/flux-hooks#readme",
27+
"devDependencies": {
28+
"eslint": "^5.16.0",
29+
"eslint-config-airbnb": "^17.1.0",
30+
"eslint-plugin-import": "^2.17.2",
31+
"eslint-plugin-jsx-a11y": "^6.2.1",
32+
"eslint-plugin-react": "^7.13.0"
33+
}
34+
}

0 commit comments

Comments
 (0)