Home > Back-end >  Non stop queries being called even though there is no loop Javascript
Non stop queries being called even though there is no loop Javascript

Time:08-20

For some reason I can both successfully send the data to the localhost:8000/data and successfully retrieve it from my front end, but when I refresh my front end it endlessly calls the query. If I just run the server, it connects to the database 1 time as it should.

Here's the server.js

const port = 8000

const express = require('express')
const cors = require('cors')
require('dotenv').config()
const axios = require('axios')

const app = express()
app.use(cors())


const mysql = require('mysql');

var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "",
port: "3306"
});
    
connection.connect((err) =>{
if(err){
    throw err
}else{
    connection.query('SELECT * FROM sg_vod_database.vod_data', (err, rows) =>{
        if(err){
            throw err;
        }else{
            console.log(rows)
        }
    })
}
})
})

app.get('/data', (req, res) =>{
    const databaseData = {
        method: "GET",
        url: "http://localhost:8000/data"
    }

    connection.query('SELECT * FROM database name', (err, rows) =>{
        if(err){
            throw err;
        }else{
            res.json(rows)
        }
    })

    axios.request(databaseData).then((response) => {
        console.log(response.data) 
    }).catch((error)=>{
        console.error(error)
    })

}) 

app.listen(port, ()=> console.log(`Server running on port ${port}`))

and here's the relevant part of the react component I am using

function VODDisplay(props) {

var dataArray = []


    const databaseData = {
        method: 'GET',
        url: 'http://localhost:8000/data'
    }

    axios.request(databaseData).then((response) => {
        console.log(response.data)
        dataArray = response.data    
    }).catch((error)=>{
        console.error(error)
    })

Do I just have code in the wrong spots? I'm unsure how much should be in the app.get, but I wonder if the front end is just calling the axios.request constantly. I did try to do useEffect to have it only run once but that didn't stop it.

CodePudding user response:

As I can see you make request whenever component is render. For react you must wrap your request in useEffect hook with empty deps array and use useState for dataArray it prevents your component to run request after each rerender

import {useEffect, useState} from 'react';

const [dataArray, setDataArray] = useState([]);

useEffect(() => {
    const databaseData = {
        method: 'GET',
        url: 'http://localhost:8000/data'
    }

    axios.request(databaseData).then((response) => {
        console.log(response.data)
        
        setDataArray(response.data); 
    }).catch((error)=>{
        console.error(error)
    })
}, [])
  • Related