skip to Main Content

I have a React state variable for an array of todos, each of which is a javascript object with a "daysRemaining" property. At the start of every day (12 AM), I want to iterate through this array and decrement the keys by 1. Right now I have no clue how to do this as I am storing this array in localStorage and the only time the node server runs is when I run npm start. If I were to host this application for many users and have a dedicated server running 24/7 how would I accomplish this daily update?

2

Answers


  1. Your state variable should be listening or fetched from a backend, then your backend should have a cronjob to update the keys.

    Login or Signup to reply.
  2. You can achieve this by setup cronjob and socket.io by this whenever cron job hits at midnight you have to call socket on your backend and receive the signals on your frontend and then you can update the state

    Backend

    // server.js
    const cron = require('node-cron');
    const express = require('express');
    const app = express();
    const http = require('http').createServer(app);
    const io = require('socket.io')(http);
    
    let currentDate = new Date();
    
    // Schedule the daily task to trigger at the start of every day (midnight)
    cron.schedule('0 0 * * *', () => {
      // Send a signal to the client on every start of the day
      io.emit('newDay');
      currentDate = new Date(); // Update the current date
    });
    
    http.listen(3001, () => {
      console.log('Server running on http://localhost:3001');
    });
    

    Front end

    // App.js
    import React, { useEffect, useState } from 'react';
    import socketIOClient from 'socket.io-client';
    
    const socket = socketIOClient('http://localhost:3001');
    
    const App = () => {
      const [stateVariable, setStateVariable] = useState(0);
    
      useEffect(() => {
        // Listen for the 'newDay' event from the server
        socket.on('newDay', () => {
          // Perform any state updates you need at the start of every day
          setStateVariable((prevValue) => prevValue + 1);
        });
    
        return () => {
          socket.disconnect();
        };
      }, []);
    
      return (
        <div>
          <h1>{stateVariable}</h1>
          {/* Other components and content */}
        </div>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search