Writing Data

Writing Data to your Firebase Realtime Database

Let's start by adding a way to the user to add data to the their firebase database.

To do this we will be using the FirebaseDatabaseMutation component from @react-firebase/database.

User Input UI

When a user clicks on the + button we want to push data to user_bookmarks/

The data should have the following shape :

{
    link_url: string,
    link_description: string,
    created_at: timestamp,
    updated_at: timestamp
}
<FirebaseDatabaseMutation type="push" path="user_bookmarks">
  {({ runMutation }) => (
    <form
      onSubmit={ev => {
          ev.preventDefault();
          const newLink = get(this.newLinkTextFieldRef, "current.value", "");
          const newMeta = get(this.newLinkMetaTextFieldRef, "current.value", "");
          await runMutation({
            link_url: newLink,
            link_description: newMeta,
            created_at: firebase.database.ServerValue.TIMESTAMP,
            updated_at: firebase.database.ServerValue.TIMESTAMP
          });
          set(this.newLinkTextFieldRef, "current.value", "");
          set(this.newLinkMetaTextFieldRef, "current.value", "");
      }}
    >
      <input label="New Link URL" ref={this.newLinkTextFieldRef} />{" "}
      <input label="New Link Metadata" ref={this.newLinkMetaTextFieldRef} />{" "}
      <button type="submit"> + </button>
    </form>
  )}
</FirebaseDatabaseMutation>;

You can see the full code here.

Last updated