"TypeError: failed to fetch" on page refresh.
Im getting the fetch error "TypeError: failed to fetch" when I refresh the page, but the issue just happens if i pass a state as fetch parameter, otherwise the application run fine.
That's the code:
const \[posts, setPosts\] = useState(\[\])
//Get posts
useEffect(() => {
fetch("https://codeleap-test-api.herokuapp.com/posts", {
method: "GET",
headers: {
"Content-type": "application/json",
}
})
.then(resp => resp.json())
.then(data => setPosts(data))
.catch(err => alert(err))
}, [])
// create new post
function createPost(post) {
fetch("https://codeleap-test-api.herokuapp.com/posts", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(post)
})
.then(resp => resp.json())
.then(data => console.log('Posts created'))
.catch(err => console.log(err))
}`
Now, if I pass the state "posts" inside the first useEffect brackets, I always get the error mentioned above. Like that:
//get posts useEffect(() => {fetch...}, [posts])
What can I do to solve the problem?
Thanks in advance!