React Hooks + Socket.io

Asked

Viewed 1,023 times

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 registerToSocket within some useEffect? Enter the complete component code...

  • This is basically the logic code of the component... function registerToSocket() {&#xA; const socket = io('http://localhost:3333');&#xA; socket.on('posts', (newPost) => {&#xA; setPost({ posts: [newPost, ...posts] });&#xA; });&#xA; }&#xA;&#xA; useEffect(() => {&#xA; async function getPost() {&#xA; try {&#xA; const response = await api.get('/posts');&#xA; console.log(response.data);&#xA; setPost(response.data);&#xA; } catch (error) {&#xA; console.log(error);&#xA; if (error) alert('Deu rium na request');&#xA; }&#xA; }&#xA; getPost();&#xA; }, []);

1 answer

0

I’ve solved that problem, basically the function registerToSocket didn’t necessarily need to be inside a useEffect to trigger the sockets, I was basically using a variable different from the emits within the backend. And also within the function, I was setting a new object for the state, and I should just pass the vector of the new posts and pass on all the posts that are already within the state.

The corrected function was this way:


function registerToSocket() {
    const socket = io('http://localhost:3333');
    socket.on('post', (newPost) => {
      setPost({[newPost, ...posts] });
    });
  }


Browser other questions tagged

You are not signed in. Login or sign up in order to post.