We will create a simple hook for fetching data from url
http://jsonplaceholder.typicode.com
We will call http://jsonplaceholder.typicode.com/users and http://jsonplaceholder.typicode.com/posts url
To avoid duplicity of code we will create a useFetch hook and pass a url parameter to it.
const useFetch = (url) => {
...
};
Watch the video here on my channel
Step 1 : Install axios for fetching data and react-router-dom for routing
npm i --save axios react-router-dom
Step 2 : create useFetch hook for fetching data
import {useEffect, useState} from 'react';
import axios from 'axios';
const useFetch = (url) => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const fetchData = () => {
axios.get(url).then((res) => {
setData(res.data);
setIsLoading(false);
});
};
useEffect(() => {
fetchData();
}, []);
return {data, isLoading};
};
export default useFetch;
Step 3 : Call the useFetch hook in Users and Posts components
Users.js
import React from 'react';
import useFetch from '../../hooks/useFetch';
const Users = () => {
let url = 'https://jsonplaceholder.typicode.com/users';
const {data, isLoading} = useFetch(url);
return (
<div className=" container ">
<div className="card ">
<div className="card-body">
{!isLoading && data.map((m, i) => <div key={i}>{m.name}</div>)}
</div>
</div>
</div>
);
};
export default Users;
Posts.js
import React from 'react';
import useFetch from '../../hooks/useFetch';
const Posts = () => {
let url = 'https://jsonplaceholder.typicode.com/posts/1';
const {data, isLoading} = useFetch(url);
return (
<div>{!isLoading && 'Title : ' + data.title + ' Body : ' + data.body}</div>
);
};
export default Posts;
Step 4 Configure Route in App.js
App.js
import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom';
import Users from './components/Users/Users';
import Posts from './components/Users/Posts';
<Router>
<Header></Header>
<Switch>
<Route path="/users" component={Users} />
<Route path="/posts" component={Posts} />
</Switch>
</Router>
Step 5: Setting up link in Header.js to call the Components
Header.js
import {NavLink} from 'react-router-dom';
<NavLink to="/users" activeClassName="activeClass">
Users
</NavLink>
<NavLink to="/posts" activeClassName="activeClass">
Posts
</NavLink>
If you had any value adds, don't forget to subscribe my youtube channel
Top comments (0)