Home > other >  Array of buttons with Navigate on Firebase and React?
Array of buttons with Navigate on Firebase and React?

Time:11-16

What i'm trying to do here is:

-Getting all of my docs in my collection in my Cloud Firestore -Putting them in an array of Buttons -Having each button navigate onPress with the info from that button in particular, since i need it for the screen it navigates to

I did it before, but it was with a JSON and using array.map:

{aulas.map((aula)  => (
                <div key={aula.id} className="col-md-4" style={{paddingBottom: '10px', paddingTop: '5px'}}>
                <Button className={(aula.estado==='sucio'? 'btn btn-danger': 'btn btn-success')} 
                onClick={()=> navigate('/LimpiarCurso',
                {state: {id:aula.id,num_aula:aula.num_aula,año:aula.año,
                division:aula.division,horario_retiro:aula.horario_retiro}})}>
                    {aula.año}{aula.division}</Button>
                </div>
            ))}

And now i'm trying to rewrite that same functionality with the database

This is what i have so far:

export default function AdministrarCurso(){
    const navigate= useNavigate();
    function mostrarCursos(navigate){
        const querySnapshot = getDocs(collection(db, "Curso"));
        querySnapshot.forEach((doc) => {
            // console.log(doc);
            // console.log(doc.data());
            console.log(doc.get('anio') doc.get('division'));
            <div className="col-md-4" style={{paddingBottom: '10px', paddingTop: '5px'}}>
            <Button 
            className={(doc.get('estado')==='sucio'? 'btn btn-danger': 'btn btn-success')} 
            onPress={()=> navigate('/LimpiarCurso',
            {state: doc.data()})}>
                {doc.get('anio') doc.get('division')}
            </Button>
            </div>
    });
    }
    return(
        <Container> 
            <AppBar style={{background: 'transparent', boxShadow: 'none'}}>
                <Toolbar>
                    <Button onClick={()=> LogOut(navigate)}>Cerrar Sesión</Button>
                </Toolbar>
            </AppBar>
             <div className="row">
             
            {mostrarCursos()}
                 {/* Acá hay botones que se generan en base a la cantidad de documentos que tenga el forEach
//                 Que te redireccionan a la pantalla de Limpiar Curso
//                  */}
             </div>
         </Container>
     )
 }

Of course, it doesn't work, since first it said that "Objects are not valid as a react child" which i tried to change but i'm not exactly sure of how to do it, i tried with useState and useEffect but it didn't really work

Now it doesn't even work with querySnapshot (it says it's not a function)

What am i doing wrong?

CodePudding user response:

The React render cycle is synchronous. Fetch the documents in a useEffect hook and map the documents to an array of doc data and properties and save it into local state to be mapped to JSX in the component's render return. getDocs returns a Promise so it should be awaited.

export default function AdministrarCurso() {
  const navigate= useNavigate();

  const [docs, setDocs] = useState([]);

  useEffect(() => {
    const mostrarCursos = async () => {
      const querySnapshot = await getDocs(collection(db, "Curso"));

      const docs = [];

      querySnapshot.forEach((doc) => {
        docs.push({
          data: doc.data(),
          anio: doc.get('anio'),
          division: doc.get('division'),
          estado: doc.get('estado'),
        });
      });
      setDocs(docs);
    };

    mostrarCuros();
  }, []);

  return(
    <Container> 
      <AppBar style={{background: 'transparent', boxShadow: 'none'}}>
        <Toolbar>
          <Button onClick={() => LogOut(navigate)}>
            Cerrar Sesión
          </Button>
        </Toolbar>
      </AppBar>
      <div className="row">
        {docs.map(doc => (
          <div
            className="col-md-4"
            style={{ paddingBottom: '10px', paddingTop: '5px' }}
          >
            <Button 
              className={doc.estado === 'sucio'
                ? 'btn btn-danger'
                : 'btn btn-success'
              } 
              onPress={()=> navigate('/LimpiarCurso', { state: doc.data })}
            >
              {doc.anio   doc.division}
            </Button>
          </div>
        ))}
      </div>
    </Container>
  )
}
  • Related