I am new to React.js, and I am trying to fetch from an api into a state . But when I do this, after a change in the json code from the api or after some time, I get infinite errors: TypeError: Failed to fetch and Posts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED .
My posts controller:
import React, { useState } from 'react';
import Post from './Post';
import axios from 'axios';
const Posts = () => {
const [posts, setPosts] = useState([]);
fetch("http://localhost:3000/data")
.then(res => res.json())
.then(
(result) => {
setPosts((prev) => prev = result);
}
)
.catch((error) => {
console.log(error);
});
return (
posts.map((post, index) => (
<Post name={post.name} content={post.content} key={index}/>
))
);
}
export default Posts;
fetchinside auseEffect(fn, [])