DEV Community

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

Posted on

4 2

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)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

DEV works best when you're signed in—unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay