DEV Community

Cover image for Handling API requests in react js
Praveen Kumar
Praveen Kumar

Posted on

Handling API requests in react js

  1. Setting Up react app
npx create-react-app apihandling
Enter fullscreen mode Exit fullscreen mode
  1. Install axios module
npm install axios
Enter fullscreen mode Exit fullscreen mode

3.In app.js file you need to import the axios module

import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode
  1. Call the API and set it into the state

Import the useState and useEffect module from react

import react, {useState, useEffect} from 'react';
Enter fullscreen mode Exit fullscreen mode

creating state to store API data

const [ApiData, setApiData] = useState([])
Enter fullscreen mode Exit fullscreen mode

Creating an async function for get an data from an API

const getData = async() => {
    const res = await axios.get("https://jsonplaceholder.typicode.com/todos")
    setApiData(res.data)
}
Enter fullscreen mode Exit fullscreen mode

Adding getData function into useEffect function

useEffect(() => {
    getData();
}, [])
Enter fullscreen mode Exit fullscreen mode
  1. In the return statement you can going to map through the value of the state Api Data
return (
    ApiData.map((data) => <p key={data.id}>{data.title}</p>)
)
Enter fullscreen mode Exit fullscreen mode

In the above code we are mapping through each value of the ApiData state and returning only the title from it in a order.

That's it we have successfully create an react app that can get api from other sources and display.

Full Code Here:

import react, {useState, useEffect} from 'react';
import axios from axios;
export default function App() {
    const [ApiData, setApiData] = useState([]);

    const getData = async() => {
        const res = await axios.get(https://jsonplaceholder.typicode.com/todos)
        setApiData(res.data)
    }

    useEffect(() => {
        getData();
    }, []);

    return (
        {
          ApiData.map((data) => <p key={data.id}>{data.title}</p>
        }
    )
}
Enter fullscreen mode Exit fullscreen mode

Thanks for Reading
Follow me on twitter @abipravi1
Image description

Top comments (0)