DEV Community

Hemant Govekar
Hemant Govekar

Posted on • Edited on

1 2

Simple Hook to fetch data (ReactJs)

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) => {
 ...
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

If you had any value adds, don't forget to subscribe my youtube channel

Watch the video here on my channel

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more