Last active
June 30, 2021 22:15
-
-
Save davvit/b0b22d4f96601fb66aee09ae652b92b5 to your computer and use it in GitHub Desktop.
React hooks data loading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useEffect, useState} from 'react'; | |
import axios from "axios"; | |
import UserComponent from "./UserComponent"; | |
const USER_SERVICE_URL = 'https://jsonplaceholder.typicode.com/users'; | |
function UserFetchUsingHook() { | |
//example of fetching data | |
const [data, setData] = useState({users: [], isFetching: false}); | |
//array argument passed to useEffect tells the Hook to run the function only | |
//if the state variables listed in the array are changed. | |
useEffect(() => { | |
const fetchUsers = async () => { | |
try { | |
setData({users: data.users, isFetching: true}); | |
const response = await axios.get(USER_SERVICE_URL); | |
setData({users: response.data, isFetching: false}); | |
} catch (e) { | |
console.log(e); | |
setData({users: data.users, isFetching: false}); | |
} | |
}; | |
fetchUsers(); | |
}, []); | |
return <UserComponent data={data.users} | |
isFetching={data.isFetching}/> | |
} | |
export default UserTableReactHooks |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment