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

166
Visualizações
Creating dynamic buttons

Trying to create a small app as part of a university assignment using React. The basic assignment is to create a page which has a question and then has one of 5 answers. I have the answers now stored in a firestore document.

I have created (the start of) a custom Button component.

So the code I have does contact the firestore and I get the data back. The examples I have tried in uni have been for getting 1 bit of data - not like this. What I'm trying to do is to create an answers "array" which I can then iterate over and create my custom buttons. However, I can't quit figure out how to create the array of answers.

Can anyone give me a hint?

import React, {useEffect, useState} from 'react';
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/storage';
import Button from '../components/Button';

function AnswerComponent() {

  const firestore = firebase.firestore();
  //const storage = firebase.storage();
  const collectionId = "Balances";
  const documentId = "Answers"

  const [answers, setAnwsers] = useState([]);

  useEffect(() => {
    const getFirebase = async () => {
      const snapshot = await firestore.collection(collectionId).doc(documentId).get();
      const questionData = snapshot.data();      

      // now we add the answers and correct flag to our answers
      const answerArr = [];
      Object.keys(questionData).forEach(key => {
        answerArr.push(questionData[key]); 
        setAnwsers(answerArr)
      });      
    };
    getFirebase();
  },[answers, firestore])

  console.log(">>", answers)
  
  return (
    <div className="col-12">
      <h3 className="text-center">Answer</h3>
      <div className="p-3 mb-2 bg-light">
      <div className="row">
        
      </div>
        {/* {btns} */}
      </div>
    </div>     
  )
}

export default AnswerComponent;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Need to push new answers onto the array, this solution saves each answer as an object with a key (preserving the key).

      const answerArr = [];
      Object.keys(questionData).forEach(key => {
        answerArr.push({ [key]: questionData[key] });
        setAnswers(newAnswerArr);
      });

If you don't need the key you could save a step and use Object.values:

      const answerArr = [];
      Object.values(questionData).forEach(questionValue => {
        answerArr.push(questionValue);
      });
        setAnwsers(answerArr);

Or with either solution you could reduce instead of setting the anwserArr separately:

const answerArr = Object.values(questionData).reduce((acc, questionValue) => {
        acc.push(questionValue)
        return acc;
      }, []);
      setAnswers(answerArr)
about 4 years ago · Juan Pablo Isaza Relatório

0

It looks like you're trying to setAnswer several times in a row (which will change the answer) when you do this:

Object.keys(questionData).forEach(key => {
    console.log(key, questionData[key]);
    setAnwsers(key, questionData[key])        
  });

Instead, I would try to create a singe array, then setAnswers to that array

const answerArray = []
Object.keys(questionData).forEach(key => {
    console.log(key, questionData[key]);
    answerArray.push(questionData[key]);    
  });
setAnswers(answerArray)
about 4 years ago · Juan Pablo Isaza Relatório

0

Turns out either piece code works (thanks to both @chris-bradshaw and @radicalturnip. The issue was I forgot useEffect changes on every change. So useEffect was triggered, getting data, that was triggering a change, which ran useEffect, which got more data and triggered another change, etc etc x infinitity.

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