Skip to content

Commit 9fe3149

Browse files
committed
update data hooks example
1 parent 83134cb commit 9fe3149

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

src/useDataApiHook-example/index.js

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import React, { Fragment, useState, useEffect } from 'react';
22
import axios from 'axios';
33

4-
const useDataApi = (url, defaultSearch, defaultState) => {
5-
const [data, setData] = useState(defaultState);
6-
const [search, setSearch] = useState(defaultSearch);
4+
const useDataApi = (initialUrl, initialData) => {
5+
const [data, setData] = useState(initialData);
6+
const [url, setUrl] = useState(initialUrl);
77
const [isLoading, setIsLoading] = useState(false);
88
const [isError, setIsError] = useState(false);
99

@@ -13,7 +13,7 @@ const useDataApi = (url, defaultSearch, defaultState) => {
1313
setIsLoading(true);
1414

1515
try {
16-
const result = await axios(`${url}${search}`);
16+
const result = await axios(url);
1717

1818
setData(result.data);
1919
} catch (error) {
@@ -22,32 +22,35 @@ const useDataApi = (url, defaultSearch, defaultState) => {
2222

2323
setIsLoading(false);
2424
},
25-
[search],
25+
[url],
2626
);
2727

28-
const doSearch = (event, query) => {
29-
setSearch(query);
28+
const getRequest = (event, url) => {
29+
setUrl(url);
3030
event.preventDefault();
3131
};
3232

33-
return { data, isLoading, isError, doSearch };
33+
return { data, isLoading, isError, getRequest };
3434
};
3535

36-
const INITIAL_SEARCH = 'redux';
37-
const INITIAL_DATA = { hits: [] };
38-
3936
function App() {
40-
const [query, setQuery] = useState(INITIAL_SEARCH);
37+
const [query, setQuery] = useState('redux');
4138

42-
const { data, isLoading, isError, doSearch } = useDataApi(
43-
'http://hn.algolia.com/api/v1/search?query=',
44-
INITIAL_SEARCH,
45-
INITIAL_DATA,
39+
const { data, isLoading, isError, getRequest } = useDataApi(
40+
'http://hn.algolia.com/api/v1/search?query=redux',
41+
{ hits: [] },
4642
);
4743

4844
return (
4945
<Fragment>
50-
<form onSubmit={event => doSearch(event, query)}>
46+
<form
47+
onSubmit={event =>
48+
getRequest(
49+
event,
50+
`http://hn.algolia.com/api/v1/search?query=${query}`,
51+
)
52+
}
53+
>
5154
<input
5255
type="text"
5356
value={query}

0 commit comments

Comments
 (0)