4

I am working on API Get request. I have created a POST request to add the data in firebase realtime database. The code is as follows:

// CREATE POST
app.post("/post", (req, res) => {
  let key;

firebase.auth().onAuthStateChanged((user) => {
if (user) {
  // User is signed in.

  var newPost = firebase.database().ref("posts/");

  var myPost = newPost.push({
    createdBy: user.uid,
    from: req.body.from,
    to: req.body.to,
    duration: req.body.duration,
    comments: req.body.comments,
  });

  res.send(newPost);
  const postId = myPost.key;
  console.log(postId);
} else {
  // No user is signed in.
  res.status(404).send("No user is signed in right now!");
}
  });
});

The following data is created in the database

Now, in order to get a specific post, I have written the following code:

// GET SPECIFIC POST
app.get("/post/:id", (req, res) => {

  let response;
  firebase
    .database()
    .ref("posts/" + req.params.id)
    .on("value", (snapshot) => {
      response = snapshot.val();
    });
  res.send(response);
});

I am new at Firebase, so I dont really know how to get a specific post. Please help me out

Adeena Lathiya
  • 165
  • 1
  • 11

2 Answers2

1

Calls to Firebase are asynchronous, because they require a call to the server. While that call is happening, your main code continues. And then when the data is available, your callback is invoked with the data from the server.

Right now your res.send(response) runs before the response = snapshot.val() is ever called. The rule with asynchronous APIs is simple: any code that needs the data needs to be inside the callback, or be called from there.

So in your case:

app.get("/post/:id", (req, res) => {
  firebase
    .database()
    .ref("posts/" + req.params.id)
    .once("value")
    .then((snapshot) => {
      res.send(snapshot.val());
    });
});

You'll note that I also change from on to once, since you only care about getting the value once (instead of attaching a permanent listener that monitors the database for changes).

Dealing with asynchronous API is a common stumbling block, so I recommend spending some time reading these answers to learn more:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

I simply did this:

app.get("/post/:id", (req, res) => {

var key = req.params.id;
  console.log(key);

 firebase
    .database()
    .ref("posts")
    .child(key)
    .get()
    .then((snapshot) => {
      res.send(snapshot.val());
    });
});

this solved the problem

Adeena Lathiya
  • 165
  • 1
  • 11