Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
Private Route Conditional Operator in ReactJS

Seems like a trivial issue.

I have an app, where people can subscribe through "stripe". Would like to give access to a few URLs based on subscription, otherwise taking them back to the "profile" page.

A couple of things are not working.

  1. Firebase query to get subscription is not giving results on the subscription. Somehow the onSnapShot does not fetch anything. Probably since UID is null at the start of rendering of page.

  2. Conditional operator on is not working. Not sure what the problem is on this one.



function PaidRoutes(props) {


  const [subscription, setSubscription] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const unsub = auth.onAuthStateChanged((authObject) => {
      unsub();
      if (authObject) {
        setLoading(true);
        const uid = auth.currentUser?.uid;
        console.log('UID ==>', uid);
        let docRef = query(collection(db, 'customers', uid, 'subscription'));
        console.log('DOC REF ==> ', docRef);
        onSnapshot(docRef, (snap) => {
          snap.forEach((doc) => {
            console.log('Role of Subscription', doc.data().role);
            setSubscription(doc.data().role);
          });
        });
      } else {
        console.log('not logged in');
        setLoading(false);
      }
    });
    return () => {
      unsub();
    };
  }, []);



  return (
    <Route
      {...props}
      render={(props) =>
        subscription ? (
          <Component {...props} />
        ) : (
          <Redirect to='/profileScreen' />
        )
      }
    />
  );

Thanks Drew for comment. The installed version of react-router-dom is 5.2.0

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Issue(s)

Potential issues I see in the PaidRoute code:

  1. The unsubscribe function is called in the auth state handler, this might allow the auth check to work once on an initial auth change, but then will unsubscribe itself and stop working until the component remounts.
  2. The loading state is initially false so any check based on it on the initial render won't do what you want. The loading also isn't used to hold off on the conditional rendering.
  3. The subscription state is initially an empty array which is still truthy, so the conditional logic checking it will likely allow access to the protected route anyway, regardless of any auth status.

Solution

  1. Don't unsubscribe from the auth change listener in the callback.
  2. Start with loading initially true to handle the initial render cycle. Conditionally render null or some loading indicator.
  3. Start with null subscription state.

Code:

function PaidRoutes(props) {
  const [subscription, setSubscription] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((authObject) => {
      if (authObject) {
        setLoading(true);
        const uid = auth.currentUser?.uid;
        console.log('UID ==>', uid);
        const docRef = query(collection(db, 'customers', uid, 'subscription'));
        console.log('DOC REF ==> ', docRef);
        onSnapshot(docRef, (snap) => {
          snap.forEach((doc) => {
            console.log('Role of Subscription', doc.data().role);
            setSubscription(doc.data().role);
          });
        });
      } else {
        console.log('not logged in');
        setSubscription(null); // <-- reset auth state
      }
      setLoading(false); // <-- clear loading state outside if-else
    });

    return unsubscribe;
  }, []);

  if (loading) {
    return null; // or loading indicator, spinner, etc...
  }

  return subscription ? (
    <Route {...props} />
  ) : (
    <Redirect to='/profileScreen' />
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda