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

303
Visualizações
I want to know how to got COUNT from SQL in reactjs

my request is good but i want to know how can i use my response in React.

SQL request :

    ```
    exports.countAllComments = async (req, res) => {
      const pId = req.params.id;
    
      db.query(
        "SELECT COUNT(*) FROM comments WHERE post_id = ?",
        [pId],
        (err, count) => {
          if (err) {
            res.status(500).json({ err });
            console.log(err);
          } else {
            console.log(count)
            res.status(200).json(count);
          }
        }
      );
    };
    ```
    

Front for fetch count:

```
    const [countData, setCountData] = useState(0);
    
      useEffect(() => {
        const fetchCount = async () => {
          try {
            const fetchData = await Axios.get(
              `http://localhost:3001/api/post/comment-count/${post.id}`,
              {
                headers: { Authorization: `Bearer ${test1.token}` },
              }
            );
            setCountData(fetchData.data[0]);
          } catch (err) {}
        };
        fetchCount();
      }, [post.id, test1.token]);
    
      console.log(countData);
    ```

console log return : "{COUNT(*): 4}" how can i get (4)

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

0

given your trivial example, the trivial solution would be something like -

fetchData.data[0]['COUNT(*)']

however, you should really have a think about the contract on the API, and enforce a certain return type from your API, and not just simply return the response from the SQL query. i.e. your API could possibly return an object like -

{ count: x }

where its up to your API to transform the result from the SQL query in a way that satisfies the contract, that way your React client is disconnected from your database layer and only cares about your API contract.

That way your client side becomes something like -

fetchData.data.count

which wouldn't break if the query where to be updated in some way etc.

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