Below committed code is axios. Which is working fine. But javascript fetch is not working. Let me know what is the issue in the code. How to fix it. Please explain it in a simple way. Thanks!
import React, {useEffect, useState} from 'react'
import axios from 'axios'
function Datafetching() {
const [posts, setposts] = useState([])
const getMovieRequest = async () => {
const url = `http://jsonplaceholder.typicode.com/posts`;
const response = await fetch(url);
const responseJson = await response.json()
if (responseJson.data){
setposts(responseJson.data)
console.log(responseJson.data)
}
}
useEffect(() => {
// axios.get('http://jsonplaceholder.typicode.com/posts')
// .then(res => {
// console.log(res)
// setposts(res.data)
// })
// .catch(err => {
// console.log(err)
// })
getMovieRequest()
})
return (
<div>
<ul>{
posts.map(post => <li key={post.id}>{post.title}</li>)
}
</ul>
</div>
)
}
export default Datafetching
responseData
contains the data as array, not responseData.data
:
if (responseJson){
setposts(responseJson)
console.log(responseJson)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.