Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

301
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda