All files / src/hooks useVoteOpen.ts

100% Statements 22/22
100% Branches 7/7
100% Functions 1/1
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 311x 1x   1x 6x 4x 6x   6x 5x 5x 5x 5x   5x   2x 2x 2x     3x 1x 3x   3x 6x   6x 6x  
import { useEffect, useState } from 'react';
import { isVoteOpen } from '@/utils';
 
export const useVoteOpen = (date: Date, startHour = 11, startMinute = 30) => {
  const [canVote, setCanVote] = useState(() =>
    isVoteOpen(date, startHour, startMinute),
  );
 
  useEffect(() => {
    const now = new Date();
    const mealDate = new Date(date);
    const startTime = new Date(mealDate);
    startTime.setHours(startHour, startMinute, 0, 0);
 
    if (now >= startTime) {
      // already open, nothing else to do
      setCanVote(true);
      return;
    }
 
    // schedule flip right when voting opens
    const timeout = setTimeout(() => {
      setCanVote(true);
    }, startTime.getTime() - now.getTime());
 
    return () => clearTimeout(timeout);
  }, [date]);
 
  return canVote;
};