- Setting Up react app
npx create-react-app apihandling
- Install
axios
module
npm install axios
3.In app.js file you need to import the axios module
import axios from 'axios';
- Call the API and set it into the state
Import the useState
and useEffect
module from react
import react, {useState, useEffect} from 'react';
creating state to store API data
const [ApiData, setApiData] = useState([])
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)
}
Adding getData
function into useEffect function
useEffect(() => {
getData();
}, [])
- 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>)
)
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>
}
)
}
Thanks for Reading
Follow me on twitter @abipravi1
Top comments (0)