How to Fetch Data From API in React JS?

Nov 16, 2022 . Admin

Hi Friends,

I will explain step by step tutorial on how to fetch data from api in react js. it's a simple example of fetch data from api in react js. We will use react js to fetch data from api. if you have a question about get data from api in react js then I will give a simple example with a solution. You just need to do some step to react js api data to get an example.

In this example how to fetch data from api in react js. I will explain step by step fetch data from API in react js. we will use fetch data from api fetch(). So, let's start following the example with output.

Step 1: Create React JS App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app reactjs-my-example
Step 2: Create index.js file src/index.js
import React, { useEffect,useState } from 'react';
import ReactDOM from 'react-dom/client';
import "./App.css";

function Example() {

    const [data,setData] = useState([])
    
    useEffect(()=>{
        Gettodo(1)
    },[])

    function Gettodo(id) {
        fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then((res)=>{
            res.json().then((resp)=>{
                setData([resp]);
            })
        });
    }

    return (
        <div>
            <table className='table'>
                <tr>
                    <td align="center" colspan="4">
                        <h2>How to Fetch Data From API in React JS? - Mywebtuts.com</h2>
                    </td>
                </tr>
                <tr>
                    <td>Id</td>
                    <td>Title</td>
                    <td>User Id</td>
                    <td>completed</td>
                </tr>
                {
                    data.map((value,index) => 
                        <tr key={index}>
                            <td>{value.id}</td>
                            <td>{value.title}</td>
                            <td>{value.userId}</td>
                            <td>{value.completed ? 'true' : 'false' }</td>
                        </tr>   
                    )
                }
            </table>
        </div>
    )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Example />);
src/App.css
.table{
    border:1px solid #000;
    width: 50%;
    margin:150px auto;
    border-collapse: collapse;
}
.table tr td{
    border:1px solid #000;
    padding:10px;
}
table, th, td {
    border: 1px solid;
}
Run React JS App:
npm start

Output:

I hope it can help you...

#React JS