Where should I put/handle periodic data updates in React?

I’m following the guide in https://reactjs.org/docs/thinking-in-react.html which makes sense for data that I request and update on a filter.

However, I want to have some sort of general synchronization job in the background that polls and updates an SQLite database periodically.

The question I have is if the SQLite database has detected that there was an update, how do I signal to a list component that it needs to refresh itself?

Notes:

I am thinking if it was in a context it will trigger a re-render of every component underneath it which may be problematic if I have something like a data entry form since a re-render will cause my focus to be lost

In vue land we have emit to emit custom events, but I don’t see anything like that in the API guide for React

Another approach I was thinking of was to useReducer, but it didn’t pan out on the context because it will also cause a re-render just like useState

Then I thought of having the reducer on the filtered table component but then I don’t know how to trigger it from the context.

I also tried putting in a useRef to prevent the re-render but that does not work for documented reasons which I have checked.

useCallback was supposedly the solution, but the dependencies would be triggering a rerender

After a bit more research I found that the build your own hooks is similar to what I needed. In that it uses a subscribe, unsubscribe pair for their chat API which isn’t actually coded, but I made an assumption on how this would work.

So I have a simple “API” that has a fetchData() method that I wrap in a context.

import React, { PropsWithChildren, createContext, useContext } from "react";

type IApiContext = {
  fetchData?: () => Promise<number>;
};
const ApiContext = createContext<IApiContext>({
  fetchData: undefined,
});
export function ApiProvider({ children }: PropsWithChildren<{}>) {
  const fetchData = async () => {
    return Promise.resolve(Date.now());
  };

  return (
    <ApiContext.Provider
      value={{
        fetchData,
      }}
    >
      {children}
    </ApiContext.Provider>
  );
}
export function useApi(): Required<IApiContext> {
  return useContext(ApiContext) as Required<IApiContext>;
}

I then have a data store object with a polling effect (not written in this answer) that will execute every 10 seconds and store the data locally (in this case a simple array ref). Then provide onSubscribe, onUnsubscribe callbacks. I also provided a getDataAsync() method which is what I’d be doing anyway since it does not make sense to reconsititute the data when I would’ve stored the data in a local database.

import React, {
  createContext, PropsWithChildren, useContext, useRef
} from "react";
import { usePoll } from "../hooks/usePoll";
import { useApi } from "./ApiContext";
export type UpdateCallback = (eventData: number) => Promise<void>;
type IDataStoreContext = {
  subscribe: (onUpdate: UpdateCallback) => void;
  unsubscribe: (onUpdate: UpdateCallback) => void;
  getDataAsync: () => Promise<string[]>;
};
const DataStoreContext = createContext<Partial<IDataStoreContext>>({});
export function DataStoreProvider({ children }: PropsWithChildren<{}>) {
  const { fetchData } = useApi();
  const dataRef = useRef<string[]>([]);
  const subscriptionsRef = useRef<UpdateCallback[]>([]);
  usePoll(
    async () => {
      const result = await fetchData();
      console.log("usePoll", result, subscriptionsRef.current, dataRef.current);
      dataRef.current.push("ds" + result);
      await Promise.all(subscriptionsRef.current.map((f) => f(result)));
      console.log("usePoll done")
    },
    10000,
    true
  );
  function subscribe(onUpdate: UpdateCallback) {
    console.log("subscribe");
    subscriptionsRef.current.push(onUpdate);
  }
  function unsubscribe(onUpdate: UpdateCallback) {
    console.log("unsubscribe");
    subscriptionsRef.current = subscriptionsRef.current.filter(
      (f) => f !== onUpdate
    );
  }
  async function getDataAsync() {
    return Promise.resolve(dataRef.current);
  }
  return (
    <DataStoreContext.Provider value={{ subscribe, unsubscribe, getDataAsync }}>
      {children}
    </DataStoreContext.Provider>
  );
}
export function useDataStore(): Required<IDataStoreContext> {
  return useContext(DataStoreContext) as Required<IDataStoreContext>;
}

I then use it in a component that would need the results

import React, { useEffect, useState } from "react";
import { FlatList, Text, View } from "react-native";
import { useDataStore } from "./DataStoreContext";
export function DebugComponent() {
  const { subscribe, unsubscribe, getDataAsync } = useDataStore();
  const [data, setData] = useState<string[]>([]);

  const onUpdate = async () => {
    const updated = await getDataAsync();
    // don't just use updated because I know it is using the same object, this forces the creation of a new array object.
    setData([...updated]);
  };

  useEffect(() => {
    subscribe(onUpdate);
    return () => {
      unsubscribe(onUpdate);
    };
  }, []);

  return (
    <View style={{ borderWidth: 1, borderColor: "black" }}>
      <FlatList
        data={data}
        keyExtractor={(r) => r}
        renderItem={({ item }) => <Text>{item}</Text>}
      />
    </View>
  );
}

Not exactly sure if this is ideal React thinking, but it seems to make the most sense right now.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật