Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!