0

I am having this issue where the result of the MySQL query in NodeJS keeps returning the results in the console and I am wondering why is this happenning?

Here is what I have done:

Server.js

 app.get("/api/listproduct", (req, res) => {
        db.query("SELECT * FROM products" , (err, result) => {
            if (err) {
                console.log(err);
            } else {
                console.log(result)
                res.send(result);
            }
        }
        )
    })

ShowProduct.js

   useEffect(async () => {
        const result = await axios.get('http://localhost:3000/api/listproduct'); 
        console.log(result.data)    
        setProducts(result.data);
      });

As you can see that the result are sort of looping to the console as shown here where it was supposed to just return only one set rather than many of the same sets of results.

enter image description here

What am I missing here and how to solve this? Many thanks in advance and greatly appreciate any helps. Thanks

5
  • hi Tomalak, my bad if I have caused you to misunderstand my question. I have edited the question to be clearer. Thanks Commented Aug 8, 2021 at 10:47
  • Is this a real question? console.log dude!... Commented Aug 8, 2021 at 10:47
  • hi Marc, I am new to using MySQL with Nodejs and I have edited the question to be more clear. Thanks Commented Aug 8, 2021 at 10:49
  • @Nat Your question is not clear. "keeps returning the results in the console" -> console.log Commented Aug 8, 2021 at 10:51
  • hi marc, my bad. Thanks Commented Aug 8, 2021 at 10:53

1 Answer 1

2

This has nothing to do with the Nodejs/MySQL backend, but your frontend React code.

You don't have a dependency array in your useEffect, so it's called every time the component is rendered. Since it calls setState, it causes a new render, and effectively an infinite loop of renders. If you don't have dependencies for your effect, add an empty array to make the effect get called only once.

useEffect(async () => {
  const result = await axios.get("http://localhost:3000/api/listproduct");
  setProducts(result.data);
}, []); // <- that empty array
Sign up to request clarification or add additional context in comments.

2 Comments

AKX, thanks a lot, that does solve it. thanks again
Great lateral debugging.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.