react custom hook to load data using api

Solutions on MaxInterview for react custom hook to load data using api by the best coders in the world

showing results for - "react custom hook to load data using api"
Till
24 Aug 2016
1const useDataFetching = () => {
2  const [data, setData] = useState({ hits: [] });
3  const [url, setUrl] = useState(
4    'https://hn.algolia.com/api/v1/search?query=redux',
5  );
6  const [isLoading, setIsLoading] = useState(false);
7  const [isError, setIsError] = useState(false);
8 
9  useEffect(() => {
10    const fetchData = async () => {
11      setIsError(false);
12      setIsLoading(true);
13 
14      try {
15        const result = await axios(url);
16 
17        setData(result.data);
18      } catch (error) {
19        setIsError(true);
20      }
21 
22      setIsLoading(false);
23    };
24 
25    fetchData();
26  }, [url]);
27 
28  return [{ data, isLoading, isError }, setUrl];
29}
30
31// Use it now..
32
33function App() {
34  const [query, setQuery] = useState('redux');
35  const [{ data, isLoading, isError }, doFetch] = useDataFetching();
36 
37  return (
38    <Fragment>
39      <form onSubmit={event => {
40        doFetch(`http://hn.algolia.com/api/v1/search?query=${query}`);
41 
42        event.preventDefault();
43      }}>
44        <input
45          type="text"
46          value={query}
47          onChange={event => setQuery(event.target.value)}
48        />
49        <button type="submit">Search</button>
50      </form>
51 
52      ...
53    </Fragment>
54  );
55}