0

My first ever question in SOF seems to be a bit silly but let's consider I am new to web development and creating my firsts JavaScript Applications :). I am trying to access the value of a variable to use it when dispatching. The value is the key which I get from Firebase database and I would like to pass the value to my "child" selection in "dispatch" method. This is what I did

export function addUser(name, username, image) {
  var lastIndex;
  usersRef.limitToLast(1).once("child_added", function(snapshot) {
    lastIndex = snapshot.key;
  });
  return dispatch => usersRef.child(lastIndex).set({"name": name, "username": username, "image": image});
}

lastIndex is the variable that I am trying to access in dispatch but it returns undefined

Hamed Mamdoohi
  • 131
  • 1
  • 6

1 Answers1

2

You're setting lastIndex in an event listener, at the time dispatch was called, the event has not been fired yet. To handle asynchronous call is why Redux-thunk passes dispatch to actions that returns function. A better approach will be

export function addUser(name, username, image) {
  return dispatch =>
    usersRef.limitToLast(1).once("child_added", function(snapshot) {
      const lastIndex = snapshot.key;
      // call you dispatch here
    });
}

However functions like this are better in the middleware.