Skip to content

Commit 073469a

Browse files
committed
Initial commit
1 parent 9627828 commit 073469a

9 files changed

+4133
-0
lines changed

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
node_modules/
2+
dist/
3+
yarn-error.log
4+
.vscode/

.prettierrc

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"singleQuote": true,
3+
"trailingComma": "all"
4+
}

README.md

+74
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,76 @@
11
# react-use-fetch-with-redux
2+
23
React hook to fetch/select data with simple caching
4+
5+
## This hook is for you if you...
6+
7+
- Want to feed a component data from Redux ✅
8+
- Don't want to make API calls if you already have the data ✅
9+
- Love hooks ✅
10+
11+
## Installation
12+
13+
With NPM:
14+
15+
```bash
16+
npm i --save react-use-fetch-with-redux
17+
```
18+
19+
With Yarn:
20+
21+
```bash
22+
yarn add react-use-fetch-with-redux
23+
```
24+
25+
## Usage
26+
27+
You can create your own hook that uses `useFetchWithRedux` to grab data (if needed) and pass it from the Redux store to your components:
28+
29+
**In `useThing.ts`**
30+
31+
```typescript
32+
import { useFetchWithRedux } from 'react-use-fetch-with-redux';
33+
import { getThingStart } from './actions/ThingActions'; // getThingStart is an action creator.
34+
import { getThingSelector } from './selectors/ThingSelector'; // getThingSelector is a selector.
35+
36+
const useThing = () => useFetchWithRedux(getThingsStart, getThingSelector);
37+
38+
export { useThing };
39+
```
40+
41+
For completeness, this is what `getThingSelector` could look like:
42+
43+
**In `./selectors/ThingSelector.ts`**
44+
45+
```typescript
46+
import { State } from './types'; // This is the Redux Store type
47+
48+
const getThingSelector = (state: State) => state.thing;
49+
50+
export { getThingSelector };
51+
```
52+
53+
Finally, piecing it all together, we can now elegantly use our hook in a component.
54+
55+
**In `SomeComponent.tsx`**
56+
57+
```tsx
58+
import React from 'react';
59+
import { useThing } from './useThing';
60+
import { State, Thing } from './types';
61+
62+
const SomeComponent = () => {
63+
const thing = useThing<State, Thing>();
64+
const Loading = () => <span>Loading...</span>;
65+
66+
return thing ? <Loading /> : <div>My thing: thing</div>;
67+
};
68+
```
69+
70+
## Testing
71+
72+
The project uses Jest for testing, along with [react-hooks-testing-library](https://github.com/testing-library/react-hooks-testing-library) for rendering hooks without explicitly creating harness components.
73+
74+
## Contributing
75+
76+
I welcome all contributions to this project. Please feel free to raise any issues or pull requests as you see fit :)

jest.config.js

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = {
2+
preset: 'ts-jest',
3+
testEnvironment: 'node',
4+
};

package.json

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
{
2+
"name": "react-use-fetch-with-redux",
3+
"version": "1.0.0",
4+
"main": "dist/index.js",
5+
"types": "dist/index.d.ts",
6+
"files": [
7+
"/dist"
8+
],
9+
"keywords": [
10+
"hooks",
11+
"react",
12+
"fetch",
13+
"redux"
14+
],
15+
"repository": "git@github.com:grug/react-use-fetch-with-redux.git",
16+
"author": "Dave Cooper <dave@davecooper.org>",
17+
"license": "MIT",
18+
"scripts": {
19+
"test": "jest",
20+
"build": "rimraf dist/ && tsc"
21+
},
22+
"husky": {
23+
"hooks": {
24+
"pre-commit": "pretty-quick --staged"
25+
}
26+
},
27+
"dependencies": {
28+
"react": "^16.12.0",
29+
"react-redux": "^7.1.3"
30+
},
31+
"np": {
32+
"contents": "dist"
33+
},
34+
"devDependencies": {
35+
"@testing-library/react": "^9.4.0",
36+
"@testing-library/react-hooks": "^3.2.1",
37+
"@types/jest": "^24.9.0",
38+
"@types/node": "^13.1.7",
39+
"@types/react": "^16.9.17",
40+
"@types/react-redux": "^7.1.5",
41+
"@types/react-test-renderer": "^16.9.1",
42+
"husky": "^4.0.10",
43+
"jest": "^24.9.0",
44+
"react-test-renderer": "^16.12.0",
45+
"rimraf": "^3.0.0",
46+
"ts-jest": "^24.3.0",
47+
"typescript": "^3.7.4",
48+
"pretty-quick": "^2.0.1"
49+
}
50+
}

src/index.spec.ts

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { renderHook } from '@testing-library/react-hooks';
2+
import { useSelector, useDispatch } from 'react-redux';
3+
import { Action } from 'redux';
4+
import { useFetchWithRedux } from './';
5+
6+
jest.mock('react-redux', () => ({
7+
useSelector: jest.fn(),
8+
useDispatch: jest.fn(),
9+
}));
10+
11+
const mockUseSelector = (useSelector as unknown) as jest.Mock;
12+
const mockUseDispatch = (useDispatch as unknown) as jest.Mock;
13+
const mockDispatch = jest.fn();
14+
15+
const testAction = (): Action => ({
16+
type: 'TEST',
17+
});
18+
const testSelector = <T>(value: T) => value;
19+
20+
describe('useFetchWithRedux hook', () => {
21+
beforeEach(() => {
22+
jest.resetAllMocks();
23+
mockUseDispatch.mockImplementation(() => mockDispatch);
24+
});
25+
26+
it('Calls dispatch when value does not exist in state', () => {
27+
mockUseSelector.mockImplementation(callback =>
28+
callback(testSelector(undefined)),
29+
);
30+
31+
const { result } = renderHook(() =>
32+
useFetchWithRedux(testAction, testSelector, false),
33+
);
34+
35+
expect(result.current).toEqual(undefined);
36+
expect(mockDispatch).toHaveBeenCalled();
37+
});
38+
39+
it('Returns value from state when it exists and does not dispatch action', () => {
40+
mockUseSelector.mockImplementation(callback =>
41+
callback(testSelector<number>(7)),
42+
);
43+
44+
const { result } = renderHook(() =>
45+
useFetchWithRedux(testAction, testSelector, false),
46+
);
47+
48+
expect(result.current).toEqual(7);
49+
expect(mockDispatch).not.toHaveBeenCalled();
50+
});
51+
52+
it('Does not call dispatch if emptyArrayIsFalse = false and selected data is an empty array', () => {
53+
mockUseSelector.mockImplementation(callback => callback(testSelector([])));
54+
55+
const { result } = renderHook(() =>
56+
useFetchWithRedux(testAction, testSelector, false),
57+
);
58+
59+
expect(result.current).toEqual([]);
60+
expect(mockDispatch).not.toHaveBeenCalled();
61+
});
62+
63+
it('Does call dispatch if emptyArrayIsFalse = true and selected data is an empty array', () => {
64+
mockUseSelector.mockImplementation(callback => callback(testSelector([])));
65+
66+
const { result } = renderHook(() =>
67+
useFetchWithRedux(testAction, testSelector, true),
68+
);
69+
70+
expect(result.current).toEqual([]);
71+
expect(mockDispatch).toHaveBeenCalled();
72+
});
73+
});

src/index.ts

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { useSelector, useDispatch } from 'react-redux';
2+
import { useEffect } from 'react';
3+
import { Action } from 'redux';
4+
5+
function useFetchWithRedux<State, Selected>(
6+
getDataStart: () => Action,
7+
selector: (state: State) => Selected,
8+
emptyArrayIsFalse: boolean = false,
9+
) {
10+
const dispatch = useDispatch();
11+
const selected = useSelector(selector);
12+
13+
useEffect(() => {
14+
if (
15+
!selected ||
16+
(emptyArrayIsFalse && Array.isArray(selected) && selected.length === 0)
17+
) {
18+
dispatch(getDataStart());
19+
}
20+
}, [dispatch]);
21+
22+
return selected;
23+
}
24+
25+
export { useFetchWithRedux };

tsconfig.json

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
{
2+
"compilerOptions": {
3+
/* Basic Options */
4+
// "incremental": true, /* Enable incremental compilation */
5+
"target": "ES2018" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
6+
"module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
7+
// "lib": [], /* Specify library files to be included in the compilation. */
8+
// "allowJs": true, /* Allow javascript files to be compiled. */
9+
// "checkJs": true, /* Report errors in .js files. */
10+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11+
"declaration": true /* Generates corresponding '.d.ts' file. */,
12+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
13+
// "sourceMap": true, /* Generates corresponding '.map' file. */
14+
// "outFile": "./", /* Concatenate and emit output to single file. */
15+
"outDir": "dist",
16+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17+
// "composite": true, /* Enable project compilation */
18+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
19+
// "removeComments": true, /* Do not emit comments to output. */
20+
// "noEmit": true, /* Do not emit outputs. */
21+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
22+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
23+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
24+
25+
/* Strict Type-Checking Options */
26+
"strict": true /* Enable all strict type-checking options. */,
27+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
28+
// "strictNullChecks": true, /* Enable strict null checks. */
29+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
30+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34+
35+
/* Additional Checks */
36+
// "noUnusedLocals": true, /* Report errors on unused locals. */
37+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
38+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
39+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
40+
41+
/* Module Resolution Options */
42+
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
43+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
44+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
45+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
46+
// "typeRoots": [], /* List of folders to include type definitions from. */
47+
// "types": [], /* Type declaration files to be included in compilation. */
48+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
49+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
50+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
51+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
52+
53+
/* Source Map Options */
54+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
55+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
56+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
57+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
58+
59+
/* Experimental Options */
60+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
61+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
62+
63+
/* Advanced Options */
64+
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
65+
},
66+
"include": ["src"],
67+
"exclude": ["src/*.spec.ts"]
68+
}

0 commit comments

Comments
 (0)