async-fetch 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,53 +10,58 @@ $ npm i async-fetch
10
10
 
11
11
  ## Usage
12
12
 
13
- Provide your config and handle the response.
13
+ Provide your request config and handle the response.
14
14
 
15
15
  ```javascript
16
16
  import React from "react";
17
17
  import useAsyncFetch from "async-fetch";
18
18
 
19
- const { pending, data, error, sendRequest, cancelRequest } = useAsyncFetch(
20
- "https://jsonplaceholder.typicode.com/todos/1"
21
- );
19
+ const App = () => {
20
+ const { pending, data, error, sendRequest, cancelRequest } = useAsyncFetch(
21
+ "http://localhost:5000/api/v1/"
22
+ );
22
23
 
23
- return pending ? (
24
- "Loading..."
25
- ) : data ? (
26
- "Data: " + JSON.stringify(data)
27
- ) : error ? (
28
- "Error: " + error.toString()
29
- ) : (
30
- <React.Fragment>
31
- <br />
32
- <br />
33
- <button onClick={sendRequest}>Send request.</button>
34
- <br />
35
- <br />
36
- <button onClick={cancelRequest}>Cancel request.</button>
37
- </React.Fragment>
38
- );
24
+ return (
25
+ <React.Fragment>
26
+ <button onClick={sendRequest}>Send request.</button>
27
+ <br />
28
+ <br />
29
+ <button onClick={cancelRequest} disabled={!pending}>
30
+ Cancel request.
31
+ </button>
32
+ <br />
33
+ <br />
34
+ {pending
35
+ ? "Loading..."
36
+ : data
37
+ ? JSON.stringify(data)
38
+ : error
39
+ ? "Error: " + error.toString()
40
+ : ""}
41
+ </React.Fragment>
42
+ );
43
+ };
44
+
45
+ export default App;
39
46
  ```
40
47
 
41
48
  ### Available IN Props And Definitions
42
49
 
43
- The minimum requirement for the hook is either a url string or an object with a url property.
44
-
45
- | Key | Type | Definition | Default |
46
- |----------------|----------|----------------------------------------------------------------------------------------------------------------|---------|
47
- | url | String | URL to send request to. | |
48
- | query | Object | Query parameters to include in the request (alt key name: "params"). | |
49
- | data | Object | Data object to include in the request body. | |
50
- | responseParser | String | Parser method to use on the response. | "json" |
51
- | onStart | Function | Callback function to run before the request is sent. | |
52
- | onSuccess | Function | Callback function to run after the response has been parsed. The parsed response is available in the callback. | |
53
- | onFail | Function | Callback function to run when the request responds with an error. The error is available in the callback. | |
54
- | onFinish | Function | Callback function to run when after the request has completed, regardless of success or failure. | |
55
- | useEffect | Array | Dependency array for the useEffect. | [] |
56
- | ignoreEffect | Boolean | Condition where if true the request won't send unless called using the sendRequest OUT property. | |
57
- | poll | Number | Time interval (in milliseconds) for polling. | |
50
+ The minimum requirement for the hook is either a url string or an object with a url property. It is assumed that any other property that's provided is to be used for the actual fetch.
58
51
 
59
- It is assumed that any other property that's provided is to be used for the actual fetch.
52
+ | Key | Type | Definition | Default |
53
+ | --------- | -------- | -------------------------------------------------------------------------------------------------------------- | ------- |
54
+ | url | String | URL to send request to. | |
55
+ | query | Object | Query parameters to include in the request (alt key name: "params"). | |
56
+ | data | Object | Data object to include in the request body. | |
57
+ | parser | String | Method used to parse the response. | "json" |
58
+ | onStart | Function | Callback function to run before the request is sent. | |
59
+ | onSuccess | Function | Callback function to run after the response has been parsed. The parsed response is available in the callback. | |
60
+ | onFail | Function | Callback function to run when the request responds with an error. The error is available in the callback. | |
61
+ | onFinish | Function | Callback function to run after the request has completed, regardless of success or failure. | |
62
+ | deps | Array | Dependency array for the useEffect. | [] |
63
+ | ignore | Boolean | Condition where if true the request won't send unless called using the sendRequest OUT property. | |
64
+ | poll | Number | Time interval (in milliseconds) for polling. | |
60
65
 
61
66
  ### Available OUT Props And Definitions
62
67
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "async-fetch",
3
- "version": "0.1.7",
4
- "description": "Asynchronously use fetch for requests within React components.",
3
+ "version": "0.2.0",
4
+ "description": "Use fetch asynchronously for requests within React components.",
5
5
  "main": "useAsyncFetch.js",
6
6
  "scripts": {
7
7
  "test": "echo \"Error: no test specified\" && exit 1"
package/useAsyncFetch.js CHANGED
@@ -3,34 +3,36 @@ import useInterval from "./useInterval";
3
3
 
4
4
  let controller;
5
5
 
6
- function useAsyncFetch(props, fetchProps = {}) {
6
+ function useAsyncFetch(props, props2) {
7
7
  let {
8
8
  url,
9
9
  query,
10
10
  params,
11
11
  data: requestData,
12
- responseParser = "json",
12
+ parser = "json",
13
13
  onStart,
14
14
  onSuccess,
15
15
  onFail,
16
16
  onFinish,
17
- ignoreEffect,
18
- useEffect: useEffectDependency = [],
17
+ deps = [],
18
+ ignore,
19
19
  poll,
20
- ...fetchProps2
21
- } = props && props.constructor === Object ? props : {};
20
+ ...props3
21
+ } = props instanceof Object ? props : {};
22
22
 
23
- if (props && props.constructor === String) url = props;
23
+ if (typeof props === "string") url = props;
24
24
 
25
25
  const [pending1, setPending1] = useState();
26
+
26
27
  const [pending2, setPending2] = useState();
28
+
27
29
  const [error, setError] = useState();
30
+
28
31
  const [data, setData] = useState();
32
+
29
33
  const [unmounted, setUnmounted] = useState();
30
34
 
31
- function cancelActiveRequest() {
32
- if (controller && controller.abort) controller.abort();
33
- }
35
+ const cancelActiveRequest = () => controller?.abort?.();
34
36
 
35
37
  async function sendRequest() {
36
38
  try {
@@ -38,17 +40,6 @@ function useAsyncFetch(props, fetchProps = {}) {
38
40
 
39
41
  controller = new AbortController();
40
42
 
41
- const options = {
42
- signal: controller && controller.signal,
43
- ...fetchProps,
44
- ...fetchProps2,
45
- };
46
-
47
- if (query || params)
48
- url += "?" + new URLSearchParams(query || params).toString();
49
-
50
- if (requestData) options.body = JSON.stringify(requestData);
51
-
52
43
  if (!unmounted) {
53
44
  if (pending1) {
54
45
  setPending2(true);
@@ -57,12 +48,26 @@ function useAsyncFetch(props, fetchProps = {}) {
57
48
  if (onStart) onStart();
58
49
  }
59
50
 
60
- const response = await fetch(url, options);
51
+ if (query || params)
52
+ url += "?" + new URLSearchParams(query || params).toString();
53
+
54
+ const response = await fetch(url, {
55
+ signal: controller?.signal,
56
+ body: requestData && JSON.stringify(requestData),
57
+ ...props2,
58
+ ...props3,
59
+ });
61
60
 
62
61
  if (!response.ok)
63
- throw new Error(response.statusText || response.status.toString());
62
+ throw new Error(
63
+ JSON.stringify({
64
+ code: response.status,
65
+ text: response.statusText,
66
+ response: await response.text(),
67
+ })
68
+ );
64
69
 
65
- const parsedResponse = await response[responseParser]();
70
+ const parsedResponse = await response[parser]();
66
71
 
67
72
  if (!unmounted) {
68
73
  setData(parsedResponse);
@@ -70,8 +75,13 @@ function useAsyncFetch(props, fetchProps = {}) {
70
75
  }
71
76
  } catch (error) {
72
77
  if (!unmounted && error.name !== "AbortError") {
73
- setError(error);
74
- if (onFail) onFail(error);
78
+ let errorJson;
79
+ try {
80
+ errorJson = error.toString().replace("Error:", "");
81
+ errorJson = JSON.parse(errorJson.trim());
82
+ } catch {}
83
+ setError(errorJson || error);
84
+ if (onFail) onFail(errorJson || error);
75
85
  }
76
86
  } finally {
77
87
  if (!unmounted) {
@@ -84,8 +94,8 @@ function useAsyncFetch(props, fetchProps = {}) {
84
94
  }
85
95
 
86
96
  useEffect(() => {
87
- if (ignoreEffect !== true) sendRequest();
88
- }, useEffectDependency); // eslint-disable-line
97
+ if (ignore !== true) sendRequest();
98
+ }, deps); // eslint-disable-line
89
99
 
90
100
  useInterval(() => {
91
101
  sendRequest();
package/useInterval.js CHANGED
@@ -1,19 +1,19 @@
1
1
  import { useEffect, useRef } from "react";
2
2
 
3
- const noop = () => {};
4
-
5
3
  function useInterval(callback, poll) {
6
- const savedCallback = useRef(noop);
4
+ const callbackRef = useRef(() => {}); // noop
7
5
 
8
6
  useEffect(() => {
9
- savedCallback.current = callback;
7
+ callbackRef.current = callback;
10
8
  });
11
9
 
12
10
  useEffect(() => {
13
11
  if (!poll) return;
14
- const tick = () => savedCallback.current();
15
- const id = setInterval(tick, poll);
16
- return () => clearInterval(id);
12
+ const onTick = () => callbackRef.current();
13
+ const interval = setInterval(onTick, poll);
14
+ return () => {
15
+ clearInterval(interval);
16
+ };
17
17
  }, [poll]);
18
18
  }
19
19