appy-one / acebase

A fast, low memory, transactional, index & query enabled NoSQL database engine and server for node.js and browser with realtime data change notifications
MIT License
491 stars 27 forks source link

New socket connected x30-200 times after receiving 4 items #188

Closed meaningg closed 1 year ago

meaningg commented 1 year ago

When receiving data from a remote server made on acebase-server to the frontend made on acebase-client new sockets start constantly connecting and it comes up to two hundred in a couple of seconds upd: This happens when the page is refreshed and blocks other actions with the database, such as adding new items image

Code:

import styles from "../styles/Home.module.scss";
import { useState } from "react";
import { AceBaseClient } from "acebase-client";
export default function Home() {
  const [newPostModalIsOpen, setNewPostModalIsOpen] = useState(false);
  const [postsIsLoading, setPostsIsLoading] = useState(true);
  const [posts, setPosts] = useState([]);
  const db = new AceBaseClient({
    host: "localhost",
    port: 5757,
    dbname: "mydb",
    https: false,
  });

  function getPostsList() {
    db.ref("postsTest")
      .get()
      .then((snap) => {
        const posts = [];
        const data = snap.val();
        for (let i in data) {
          posts.push(data[i]);
        }
        setPosts(posts);
        setPostsIsLoading(false);
      });
  }
  getPostsList();

  const handleSubmit = (event) => {
    event.preventDefault();

    db.ref("postsTest")
      .push({
        title: "Test",
        text: "test test test yo",
      })
      .then((postRef) => {
        setNewPostModalIsOpen(false);
      });
  }; 

(Probably my mistake here somewhere, but I can't figure out where :))

appy-one commented 1 year ago

I don't have any experience with React, but I reckon the db code is now triggered to run each redraw cycle

meaningg commented 1 year ago

Yes, it did create a new connection for each rendering. I managed to fix it by throwing the initialization of the database and the initial list to useEffect

useEffect(() => {
    return () => {
      const db = new AceBaseClient({
        host: "localhost",
        port: 5757,
        dbname: "mydb",
        https: false,
      });
      setDb(db);
      getPostsList(db);
    };
  }, []);

  function getPostsList(db) {
    db.ref("postsTest")
      .get()
      .then((snap) => {
        const posts = [];
        const data = snap.val();
        for (let i in data) {
          posts.push(data[i]);
        }
        setPosts(posts);
        setPostsIsLoading(false);
      });
  }