Home > Enterprise >  How to modify a variable in the backend via the frontened?
How to modify a variable in the backend via the frontened?

Time:05-20

so I am making a website where I sell things, and there is an indicator that shows the stock left, so that every time someone buys, it goes down by 1.

I've managed to connect my React app to my backend, and it works.

My backend :

const express = require('express')
const app = express()
const port = 5000
const number = 999
const text = number.toString();


app.get('/1', (req, res) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.send(text)
  })

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

And in my React app :

...
const Component = () => {
    const [data, setData] = useState(null);
  
    useEffect(() => {
      axios.get("http://localhost:5000/1").then(resp => setData(resp.data))
    }, []);
    
    if(data === null) {
      return <div>Still loading...</div>
    }
  
    return <div>{data}</div>
  }
...

I also have a function that allows users to buy.

How can I make the frontened "send" and information to the backend that says "Hey, decrease number that you have by 1." ?

CodePudding user response:

This should work:

const express = require('express')
const app = express()
const port = 5000
let number = 999
const text = number.toString();


app.get('/1', (req, res) => {
    res.set('Access-Control-Allow-Origin', '*');
    number -= 1
    res.send(number.toString())
  })

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

However, as the other answer states. You should ideally be looking into running a storage database like mysql or mongodb. If your server goes down, then number would reset back to 999.

CodePudding user response:

You should store this kind of data on some storage such as file or a database and modify the value when a sell was made, you can use cache solution to speed up the rounf trip between the client and server.

  • Related