- Forums
- react
- Very Simple React Fetch API Data Using Axios UseEffect and Usestate Example
import { useEffect, useState } from "react";
import axios from 'axios' [5070], Last Updated: Mon Jun 24, 2024
dd
Fri Feb 03, 2023
0 Comments
498 Visits
Follow these steps to create a very simple fetch API example
- Use fake API data: https://jsonplaceholder.typicode.com/posts
- Create a new component in your React App
- Import useEffect, useState and axios
NOTE: You may have to install axios if you don't already have it
$ npm install --save axios
- Note1: To load only once onDidMount: useEffect(() => {}) If you see useEffect loads more then once,
try this solution: https://www.webune.com/forums/ionic-typescript-react-application-useeffect-running-api-multiple-two-times-twice-duplicates.html
- Note2: To Re-render the variable everytime it changes use: ([varaiable1,variable2])
4. declare a posts useState:
const [posts, setPosts] = useState([]);
5. Add UseEffect():
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
console.log(`LINE 11 res=`, res);
setPosts(res.data)
})
.catch()
})
6. Loop through the posts
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))
}
</ul>
Complete Code:
import { useEffect, useState } from "react";
import axios from 'axios';
function Example() {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
console.log(`LINE 11 res=`, res);
setPosts(res.data)
})
.catch()
})
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))
}
</ul>
)
}
export default Example;
0ZJgIjIuY7U