kossnocorp / typesaurus-react

🦕 React/Preact Hooks for Typesaurus, type-safe Firestore ODM
90 stars 5 forks source link

Add temporary data to useOn hooks #15

Open SrBrahma opened 2 years ago

SrBrahma commented 2 years ago

Updated data may take a while to arrive. When using an API to create/update data, it's noticeable the end of the loading of the API call to the new data of Firestore to arrive and update the UI. It's strange something ending its loading and nothing changing, until it suddenly changes.

What I am currently doing is that some of my API calls returns the new document to the user. Then, I have a temporary useState that will store this new value. The db data is either this temp data if available or the fetched data itself. I also have a useEffect that when fetched data changes, it resets the temp data.

This way, there isn't that intermediary state of the end of the API call and the wait for the new data to arrive.

Example:

const [store, { error, loading }] = useOnGet(stores, storeId || undefined);
const [storeDataTemp, setStoreDataTemp] = useState<DbStore | null>(null);

const storeData = storeDataTemp ?? store?.data;

useEffect(() => {
  setStoreDataTemp(null); // reset temp data when store db data changes
}, [store?.data]);

My idea is to implement this on useOn hooks, as something like setTempData on the obj retuned by those hooks.

This would fail if somehow (network issues) the API data takes longer than the Firestore data to arrive, and the API data is already obsolete, having the Firestore already newer data. So, older data would overwrite newer data.

In my cases this isn't an issue, as those documents are not updated frequently. Maybe a workaround for more frequent cases would be having a updatedAt timestamp and only allowing using it if newer.

Maybe, the setTempData could also receive a promise of the new data. If Firestore data updates before the API promise resolve, it would discard the incoming setTempData, as it may have older data. This way it would work most of the times, and discard possible problematic ones, although rare. If the Firestore data isn't the newest yet, it will soon be updated. If it's the newest, nice! Updated before the API data arrival.

This is just an idea, maybe not good enough to be included in the lib, but I think it's worth to be shared and to see if somebody has a better solution.