0

I am currently learning nodejs and react, and I want to achieve data transmission between frontend and backend. During this, I found that every time I refresh the website, the console in the browser would print out the content several times. Here is my frontend code for post, get data and display data result.

callAPI.js

import axios from 'axios'
const api = 'http://localhost:5000'

class callAPI{
    getSomething(){
        return new Promise((resolve)=>resolve(axios.get(`${api}`)))
    }
    sendSomething(body){
        return new Promise((resolve)=>resolve(axios.post(`${api}/hello`,body)))
    }
}
export default new callAPI()`

Page.js


import React, { useState } from 'react'
import callAPI from './callAPI';

export default function Page(){
    const[content, setContent] = useState("")
    const[greeting, setGreeting] = useState("")

    function getContent(){
        callAPI.getSomething().then(response=>{
            console.log(response.data)
            setContent(response.data)
        })
    }
    function handleLB(){
        callAPI.sendSomething({name:"Sam"})
        .then((response)=>{
            console.log(response.data)
            setGreeting(response.data)
        })
    }
    function handleCC(){
        callAPI.sendSomething({name:"Mary"})
        .then((response)=>{
            console.log(response.data)
            setGreeting(response.data)
        })
    }
    getContent()
    console.log(content)
    return(
        <>
            <h1>{content}</h1>
            <div>
                <button onClick={handleLB}>Sam is comming</button>
                <button onClick={handleCC}>Mary is comming</button>
            </div>
            <div>
                <p>{greeting}</p>
            </div>
        </>
    )
}

Here is my backend code app.js

var express = require('express');
var cors = require('cors')
var app = express();

const greeting={"Sam":"Handsome boy","Mary":"Young and beautiful lady"}

var corsOptions={
    credentiala:true,
    origin:'http://localhost:3000',
    optionsSuccessStatus:200
}
app.use(cors(corsOptions))

app.use(express.urlencoded({extended:true}));
app.use(express.json());

app.get('/',function(req, res) {
    res.send('Knock knock, who\'s coming?')
})

app.post('/hello',function(req, res){
    //console.log(req.body.name)
    let grt = greeting[req.body.name]
    res.send(grt)
})
app.listen(5000,function(){
    console.log('App is listening on port 5000...')
})

And here is a picture of my browser consoleWhen i get into the website, it returns a bunch of same strings.

In my understanding, each GET/POST should only have one return results. In this case, when I POST something, I only get one return results. But for GET, I get multiple. And I'm really curious why this would happen.

csxyyyyy
  • 17
  • 3
  • 1
    You've implemented the [explicit promise construction anti-pattern](https://stackoverflow.com/q/23803743/283366). Axios already returns a promise, you don't need to create new ones – Phil Nov 22 '22 at 05:37
  • You need to move your `getContent()` call into an effect hook, otherwise it will execute on every render... `useEffect(() => { getContent(); }, []);` – Phil Nov 22 '22 at 05:39
  • @Phil So the reason that I get several same return is that every time I refresh the page, the code execute several times? And using useEffect make sure that the function getContent() only execute on time. Do I understand it correctly? – csxyyyyy Nov 22 '22 at 20:51

1 Answers1

0

First of all axios return promise by itself so don't need to put again in Promises and call getContent using useEffect.

useEffect(() => {
 getContent() 
},[])

In dependency array you can have some dependency or leave it blank(so it will call the getContent only once time)