Benjamin Sommer
Benjamin Sommer

Reputation: 1258

Firebase - hold temporary data while being sent to cloud firestore

I have a calendar driven by data from firebase. When a user makes an edit, by moving or resizing a task, it will quickly move back to its original position, then the database will update the client, and the new data will be shown on the page.

Here is a simple diagram to explain:

A - User moves task in calendar UI
↓
B - UI flicks back to its previous position
↓
C - Data is sent to Cloud Firestore
↓
D - Updated data is returned to the client via a realtime listener
↓
E - UI is updated

The delay between points A and E can be as small as 50ms, but in times as long as 1000ms.

Is there any way, after a user makes a change, to store temporary data in the user's browser that reflects the updates while the data in firestore is being updated? When the realtime listener fires, it will reset the temporary data and all will be up to date.

This is my current code to listen for changes and update the projects variable:

const [projects, loadingProjects, errorProjects] = useCollection(
    organisationID && firebase.firestore().collection('organisations').doc(organisationID).collection("projects"),
    {
      snapshotListenOptions: { includeMetadataChanges: true },
    }
  );

How would I go about implementing a system like this in React?

Upvotes: 2

Views: 761

Answers (2)

REALWISHALL
REALWISHALL

Reputation: 9

Don't know you can switch or not but one solution is use Firestore database for this purpose as in this this database even if your database is not actually updated it is intelligent enough to see the change and update the data.

Con: As it is billed according to number of times it read database this might reflect in your bill

Upvotes: 0

banyan
banyan

Reputation: 4192

One way to do this is to save the data to the local state at the first time you fetch it, and the calendar will refer to it.

That is, after the first rendering, the state is separated from firestore.

Something like this.

function App() {
  const [localData, setLocalData] = useState(null);

  useEffect(() => {
    setLocalData(dataFromFirestore)
  }, []);

  const handleClick = (data) => {
    setLocalData(data)
    saveDataToFirestore(data)
  }

  return <Calender onClick={handleClick} data={localData} />
}

Upvotes: 3

Related Questions