showing results for - "react load api data with loading indicator"
Maximilian
14 Jan 2018
1import React, { Fragment, useState, useEffect } from 'react';
2import axios from 'axios';
3 
4function App() {
5  const [data, setData] = useState({ hits: [] });
6  const [query, setQuery] = useState('redux');
7  const [url, setUrl] = useState(
8    'https://hn.algolia.com/api/v1/search?query=redux',
9  );
10  const [isLoading, setIsLoading] = useState(false);
11 
12  useEffect(() => {
13    const fetchData = async () => {
14      setIsLoading(true);
15 
16      const result = await axios(url);
17 
18      setData(result.data);
19      setIsLoading(false);
20    };
21 
22    fetchData();
23  }, [url]);
24 
25  return (
26    <Fragment>
27      <input
28        type="text"
29        value={query}
30        onChange={event => setQuery(event.target.value)}
31      />
32      <button
33        type="button"
34        onClick={() =>
35          setUrl(`http://hn.algolia.com/api/v1/search?query=${query}`)
36        }
37      >
38        Search
39      </button>
40 
41      {isLoading ? (
42        <div>Loading ...</div>
43      ) : (
44        <ul>
45          {data.hits.map(item => (
46            <li key={item.objectID}>
47              <a href={item.url}>{item.title}</a>
48            </li>
49          ))}
50        </ul>
51      )}
52    </Fragment>
53  );
54}
55 
56export default App;