Guide: How to emulate live queries without performance overhead of live queries

This guide is for react or next js.

This is how to use useSWR module to emulate live queries without having to use the live query server.
The beauty of this approach is that you have no performance overhead and bottlenecks when it comes to scaling you app that traditionally come with live query server reliant on websockets.

Also the useSWR package does request deduplication and is smart enough to refresh the page when it’s in the viewport and sleep when the page is minimized.

// client side
import useSWR from "swr";

// inside react component
const [numberOfPeople, setNumberOfPeople] = useState(0);

// this is a fetcher function to connect to the actual function in the backend

function fetchNumberOfPeople({numberOfPeople}) {
const Parse = (await import("parse")).default;
Parse.initialize(process.env.NEXT_PUBLIC_APP_ID);
Parse.serverURL = `${process.env.NEXT_PUBLIC_SERVER_URL}/parse`;

const response = await Parse.Cloud.run("getNumberOfPeople", { groupId});
  if (response && response.sts) {
    setNumOfPeople(response.msg);
  }
}

// this is the function that emulates the live queries
useSWR({ groupId, setNumberOfPeople}, fetchNumberOfPeople, { refreshInterval: 1000 }); // refresh every second;

// server side
// this is the actual function on the backend

Parse.Cloud.define("getNumberOfPeople", async (req) => {
  const { groupId} = req.params;
  try {
    const qNumOfPeople= new Parse.Query("People");
    qNumOfPeople.equalTo("groupId", groupId);
    const rNumOfPeople = await qNumOfPeople.count({ useMasterKey: true });

    if (rNumOfPeople ) {
      return { sts: true, msg: rNumOfPeople };
    } else {
      return { sts: false };
    }
  } catch (err) {
    console.log("Error in getNumberOfPeople", err.message);
    return err;
});