0

I'm a junior dev, so please be easy with me.

My goal is to auth an user anonymously when he open the homepage, then if all went ok, he fetch the data from the real time database, but only if the uid match is ok!

He there are my rules:

{
  "rules": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "false",
      }
  }
}

My database is structured like this https://ibb.co/jkRBCsF


The anonymous sign in is on the context

export const AuthContextProvider = ({ children }: Props) => {
  React.useEffect(() => {
    signInAnonymously(auth)
      .then(() => {
        // Signed in..
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ...
      });
  }, []);

  const values = {};

  return <AuthContext.Provider value={values}>{children}</AuthContext.Provider>;
};

Then when I open a page for example '/crew' getStaticProps launches fetchPlanetInfo

export const getStaticProps: GetStaticProps = async () => {
  const planetInfo = await fetchPlanetsInfo("destinations");

  return {
    props: {
      data: planetInfo,
    },
  };
};
export function fetchPlanetsInfo(query: string) {
  let dataArr: any = [];

  try {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        const uid = user.uid;
        const databaseCall = ref(db, uid + "/" + query);

        onValue(databaseCall, (snapshot) => {
          const data = snapshot.val();
          dataArr.push(data);
        });
      } else {
        console.log("user is signout");
        // User is signed out
        // ...
      }
    });
  } catch (error) {
    console.log(error);
  }

  return dataArr.flat();
}

I tried to figure out where is the error but I didn't find out the solution

My problem is that the data is not get from the database. fetchPlanetsInfo return null. I think my rules is written wrong.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Sandrew94
  • 51
  • 6
  • Can you specify the problem? – User456 Jun 12 '22 at 17:21
  • fetchPlanetsInfo return null, i think my rules are wrong – Sandrew94 Jun 12 '22 at 17:27
  • 2
    Both `onAuthStateChanged` and `onValue` are asynchronous calls that don't follow the flow you expect. Neither of them has completed by the time your `return dataArr.flat()` statement executes. I recommend adding some logging or setting breakpoints and running the code in a debugger to verify the actual flow. https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890 – Frank van Puffelen Jun 12 '22 at 19:01

0 Answers0