update component after api res

Solutions on MaxInterview for update component after api res by the best coders in the world

showing results for - "update component after api res"
Marco
02 Jun 2018
1function MyComponent() {
2  const [error, setError] = useState(null);
3  const [isLoaded, setIsLoaded] = useState(false);
4  const [items, setItems] = useState([]);
5
6  // Note: the empty deps array [] means
7  // this useEffect will run once
8  // similar to componentDidMount()
9  useEffect(() => {
10    fetch("https://api.example.com/items")
11      .then(res => res.json())
12      .then(
13        (result) => {
14          setIsLoaded(true);
15          setItems(result);
16        },
17        // Note: it's important to handle errors here
18        // instead of a catch() block so that we don't swallow
19        // exceptions from actual bugs in components.
20        (error) => {
21          setIsLoaded(true);
22          setError(error);
23        }
24      )
25  }, [])
26
27  if (error) {
28    return <div>Error: {error.message}</div>;
29  } else if (!isLoaded) {
30    return <div>Loading...</div>;
31  } else {
32    return (
33      <ul>
34        {items.map(item => (
35          <li key={item.id}>
36            {item.name} {item.price}
37          </li>
38        ))}
39      </ul>
40    );
41  }
42}