0

I am working on this QR code based application which is using a ClearDB MySQL database that is stored on Heroku servers. The frontend communicates with the database by using a REST API built with Node.js and Express

Whenever a user scans a QR code, the value of the code changes in the database. But I don't know how to reflect that change instantly in the frontend. Basically what I need help with is finding a way to automatically refresh the page whenever that value changes in the database and display the new QR code based on the new value. Such that when a user scans the code, it instantly updates on his page, not only in the database.

I looked into sockets but didn't quite understand how to integrate it into my application, especially when it comes to the frontend.

2 Answers2

0

How are you storing the information for the QR codes? In Redux? Or local state? Are you using class-based components or hooks? If you want the least amount of headaches, I'd heavily suggest hooks. Let me know and I can give more specifics for the code.

Your final product would look something like this:

const [qrData, setQrData] = useState(null)

const updateDatabase = () => {
    axios.post(`your/database/url/with/your/data/attached`).then(res => {
        setQrData(res.data.your.response.object.from.database)
    }
}

Maxwell
  • 405
  • 3
  • 8
  • I am indeed using hooks. The QR codes are stored in a table in the database. And that database is hosted on a Heroku server. Sorry if my explanations are not clear enough, I am pretty new in this and still learning – astanphaeus Jun 18 '21 at 19:37
  • That's okay. I wasn't clear either lol. I'm asking where are you storing the value of the QR code in react native. From your response though I'm pretty sure you're just using standard local state for it so I'll give you a response based on that. - Make your api call to the server - chain it with .then(res -> {}) - upon a successful response, I imagine you'll receive the updated QR data from your server - take that data and update your local state object for the QR code - since you're using hooks, the UI should re-render immediately – Maxwell Jun 18 '21 at 19:49
0

You can use a state value for detecting the change. You declare a state value of which type is boolean(any type you want). Then you can implement setState function(in case of class component) or useState hook(in case of functional component) in the module of updating data in the database. For example:

const [isChanged, setChanged] = useState(false);
const updateQRData = (data) => {
... Update codes
setChanged(isChanged => !isChanged);
}

Then you can use useEffect hook:

useEffect(() => {
... Write some codes
}, [isChanged]);
pullidea-dev
  • 1,768
  • 1
  • 7
  • 23