RPeraltaJr
11/6/2019 - 4:07 PM

Fetching Data with React Hooks

Source: https://www.robinwieruch.de/react-hooks-fetch-data

Advantages of using Axios:
Axios has built-in XSRF protection.

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import User from './components/User';

function App() {
  
  const [ users, setUsers ] = useState([]);
  
  useEffect(() => {
    async function fetchData() {
      const result = await axios('https://jsonplaceholder.typicode.com/users/');
      setUsers(result);
    }
    fetchData();
  });
  
  return (
    <div>
      {users.map( users =>
        <User 
          name={user.name}
          id={user.id}
          key={user.id.toString()} 
        />
      )}
    </div>
  );
  
}