I am building a food expiry tracker application and when food products are inserted into the application a timer starts. on refresh, the timer starts all over again. To resolve this I used browser local storage. It works but when the app is hosted and another browser opens the application, the timer starts all over again because the browser does not have the initial timer state.

How do I resolve this? do I store the timer in milliseconds in my Mongo DB? but how will the client timer update? Please how do I do this?

1

There are 1 best solutions below

0
WillPaulViz On

You can save the current time using Date.now(), or by using other methods with storing the time in a record.

Here's a quick example I made

const schema = require("./schema")

async function saveExpiry() {
    const food = 'potato'
    
    const expiryTime = Date.now() // Returns the current timestamp in milliseconds

    await schema.findOneAndUpdate({ name: food }, { expiry: expiryTime }, { upsert: true })
}

async function getExpiry() {
    const food = 'potato'

    const result = await schema.findOne({ name: food })

    const expiry = new Date(result.expiry)
    const expiryString = expiry.toLocaleString() // I have linked below where you can find different Date methods
    
    return expiryString
}
const mongoose = require('mongoose')

const food = mongoose.Schema({
    name: String,
    expiry: Number
})

module.exports = mongoose.model('food', food)

Date Methods