-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseDictionary.js
51 lines (47 loc) · 1.26 KB
/
useDictionary.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { useState, useEffect } from "react";
function useDictionary(word) {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
if (word) {
fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`, {
signal: abortCont.signal,
})
.then((res) => {
if (!res.ok) {
// error coming back from server
throw Error("word not found");
}
return res.json();
})
.then((data) => {
setIsPending(false);
setData(data);
setError(null);
})
.catch((err) => {
if (err.name === "AbortError") {
console.log("fetch aborted");
} else {
// auto catches network / connection error
setIsPending(false);
setError(err.message);
}
});
} else {
setIsPending(false);
setError(null);
}
// abort the fetch
return () => {
abortCont.abort();
setIsPending(true);
setError(null);
setData(null);
};
}, [word]);
return { data, isPending, error };
}
export default useDictionary;