0
I’m using the React Hooks for a simple application, a clone of the Instragam feed. To request each post in the api, I’m using this logic:
function Feed() {
const [posts, setPost] = useState([]);
useEffect(() => {
async function getPost() {
try {
const response = await api.get('/posts');
console.log(response.data);
setPost(response.data);
} catch (error) {
console.log(error);
if (error) alert('Deu rium na request');
}
}
getPost();
}, []);
Scrolls very well, I can render the post by scrolling through the variable "posts" which is my state within the component just declaring a post.map within my JSX.
return (
<section id="post-list">
{posts.map(post => (
<article key={post._id}>
<header>
<div className="user-info">
<span>{post.author}</span>
<span className="place">{post.place}</span>
</div>
The thing gets more complex when I try to apply Realtime with the socket.io, which is a Node lib for websockets. I set a function, call registerToSocket,
function registerToSocket() {
const socket = io('http://localhost:3333');
socket.on('posts', (newPost) => {
setPost({ posts: [newPost, ...posts] });
});
}
That makes all the sockets configuration, but I’m stuck on how to apply it within my useEffect, which is a kind of React classes' componentDidMount method, preventing from creating infinite loopings and a broken code. If anyone knows any solution, I’m grateful!
Are you putting the
registerToSocketwithin someuseEffect? Enter the complete component code...– Luiz Felipe
This is basically the logic code of the component...
function registerToSocket() {
 const socket = io('http://localhost:3333');
 socket.on('posts', (newPost) => {
 setPost({ posts: [newPost, ...posts] });
 });
 }

 useEffect(() => {
 async function getPost() {
 try {
 const response = await api.get('/posts');
 console.log(response.data);
 setPost(response.data);
 } catch (error) {
 console.log(error);
 if (error) alert('Deu rium na request');
 }
 }
 getPost();
 }, []);– Edilson Pacheco