Skip to content

Instantly share code, notes, and snippets.

@davvit
Last active June 30, 2021 22:15
Show Gist options
  • Save davvit/b0b22d4f96601fb66aee09ae652b92b5 to your computer and use it in GitHub Desktop.
Save davvit/b0b22d4f96601fb66aee09ae652b92b5 to your computer and use it in GitHub Desktop.
React hooks data loading
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