meeshaa
meeshaa

Reputation: 163

Issue with state in react using firebase

I have an application that allows the user to select a US state, Once state is selected I pull some data from my firebase database, based on the state the user selected. If the user selects "California" I expect it to pull UFO sightings from California.

Upon render my state is empty. Once I select any state lets say "Washington" my state is still empty. If i choose another state like "California" my results from Washington show up and not California, then if I choose another state like "New York" my results from California will display and not New York.. it continues in this pattern.

Any reason why this is happening? I am missing something. Below is my code, and I can also provide any other information if needed or screenshots.

const [ufoSightings, setUfoSightings] = useState([]);
const [userStateSelection, setUserStateSelection] = useState("");

  useEffect(() => {
    setUfoSightings([]);
    //referencing firebase db
    const ufoRef = firebase.database().ref("ufos");
    //filter database searching for spacific state user is looking for
    const query = ufoRef
      .orderByChild("state")
      .equalTo(`${userStateSelection}`)
      .limitToFirst(2);

    let allUfo = [];
    query.once("value").then((snapshot) => {
      //storing ufoSightings in state
      snapshot.forEach((snap) => {
        allUfo.push(snap.val());
      });
    });
    setUfoSightings(allUfo);
  }, [userStateSelection]);

  ufoSightings.map((item) => console.log(item));

Upvotes: 0

Views: 23

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38777

setUfoSightings(allUfo); will execute before query.once("value").then((snapshot) => { resolves. Try the following by moving the setUfoSightings(allUfo); inside the then:

let allUfo = [];

query.once("value").then((snapshot) => {
  snapshot.forEach((snap) => {
    allUfo.push(snap.val());
  });

  setUfoSightings(allUfo);
});

Hopefully that helps!

Upvotes: 1

Related Questions