Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

reactjs - React change value of checkbox after 24 hours

I am creating a "smart shopping list", which sees how often I buy products and when I should buy next. At my current state, I want to keep the checkbox checked for 24 hours, so I am not able to uncheck it and it should be unchecked automatically after 24 hours (this is a criterion that I have to follow). How can I write something like setTimeout in my onChange function? I really could need some help here, thank you very much for responding.

Here is my code:

import React from 'react';
import firebase from '../lib/firebase';
import Nav from './Nav';
import { useCollectionData } from 'react-firebase-hooks/firestore';

const db = firebase.firestore().collection('shopping_list');

const ItemsList = () => {
  const userToken = localStorage.getItem('token');

  const [shoppingList, loading, error] = useCollectionData(
    db.where('token', '==', userToken),
    { idField: 'documentId' },
  );

  
  const markItemAsPurchased = (index) => {
    const { items, documentId } = shoppingList[0];
    const shoppingListObject = items[index];
    if (shoppingListObject.lastPurchasedOn !== null) {
      return;
    }
    shoppingListObject.lastPurchasedOn = Date.now();
    items[index] = shoppingListObject;
    db.doc(documentId)
      .update({
        items: items,
      })
      .then(() => console.log('Successfully updated item'))
      .catch((e) => console.log('error', e));
  };
  return (
    <div>
      <h1>Your Shopping List</h1>
      <div>
        {loading && <p>Loading...</p>}
        {error && <p>An error has occured...</p>}
        {shoppingList && !shoppingList.length && (
          <p>You haven't created a shopping list yet...</p>
        )}
        <ul>
          {shoppingList &&
            shoppingList[0] &&
            shoppingList[0].items.map((shoppingItemObject, index) => {
              return (
                <li key={shoppingItemObject.shoppingListItemName + index}>
                  <label>
                    {shoppingItemObject.shoppingListItemName}
                    <input
                      type="checkbox"
                      onChange={() => markItemAsPurchased(index)}
                      checked={
                        shoppingItemObject.lastPurchasedOn === null
                          ? false
                          : true
                      }
                    />
                  </label>
                </li>
              );
            })}
        </ul>
      </div>
      <Nav />
    </div>
  );
};

export default ItemsList;
question from:https://stackoverflow.com/questions/65901897/react-change-value-of-checkbox-after-24-hours

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to everyone who tried to help me. I already got the answer, pls check it out in case you need this function too :)

I created a new function for the time:

const wasItemPurchasedWithinLastOneDay = (lastPurchasedOn) => {
  const oneDayInMilliseconds = 24 * 60 * 60 * 1000;
  return (Date.now() - lastPurchasedOn) <= oneDayInMilliseconds;
}

I used Date.now() in the if/else statement, to set the value of the actual date the item was purchased:

  const markItemAsPurchased = (index) => {
    const { items, documentId } = shoppingList[0];
    const shoppingListObject = items[index];
    if (shoppingListObject.lastPurchasedOn === null) {
      shoppingListObject.lastPurchasedOn = Date.now();
    } else {
      shoppingListObject.lastPurchasedOn = null;
    }
    

I changed the function on checked as followed:

checked={
shoppingItemObject.lastPurchasedOn === null
? false : wasItemPurchasedWithinLastOneDay(shoppingItemObject.lastPurchasedOn)                          } 

It now checks if the date of the last value is more than 24 hours and unchecks the checkbox if it is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...