Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

```
    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)

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading