Home > OS >  Is there a better way of implementing this without multiple fetch request?
Is there a better way of implementing this without multiple fetch request?

Time:03-21

This is login component from a react application and I am trying to do a simple authentication login with Firebase as my real time database.

My first approach is to execute a fetch request (GET) to see if there is any existing user. Afterwhich, if the password do match with the user, I want to update the "isLoggedIn" field to true. In order to achieve the following, another fetch request (PATCH) was made.

Therefore, I am wondering if it is a bad practice to have multiple fetch request in one function and would like to know if there is a more efficient or better way of implementing this simple application?

 const loginHandler = async (userName, password) => {
    const url = `insert_url_link_here/users/${userName}.json`;
    try {
      const response = await fetch(url);
      const user = await response.json();
      if (user.password === password) {
        await fetch(url, {
          method: "PATCH",
          body: JSON.stringify({ isLoggedIn: true }),
        });

      }
    } catch (error) {
      console.log(error);
    }

This is the schema of my database.

--users:
    eric:
        isLoggedIn: false
        password: "321"

    test:
        isLoggedIn: false
        password: "222"

CodePudding user response:

I suggest using a Firebase client implementation and looking at the Firebase documentation. There are well described and explicit examples in various languages:

https://firebase.google.com/docs/auth/web/start

Besides, I don't see the point of storing passwords or login state on your side since Firebase Auth already does this for you in a secure way.

CodePudding user response:

You're accessing the Firebase Realtime Database through its REST API, which implements simple CRUD operations, and there's no way to combine a read and a write operation into a single operation there.

The only other relevant operation is the conditional write, which you can use to only write data if it hasn't been modified since you read it. You can use this to implement an optimistic compare-and-set like transaction mechanism, but given that you're toggling a boolean it doesn't seem to apply here.


If you're on an environment that supports it, you may want to consider using the Firebase SDK for that platform, as the SDKs typically use a web socket to communicate with the server, which often ends up being a lot more efficient than performing multiple individual HTTP requests.

  • Related