Skip to content

Commit

Permalink
feat: live-updating time display on Todos
Browse files Browse the repository at this point in the history
  • Loading branch information
adekbadek committed Jul 7, 2020
1 parent 74bd271 commit 2f640ef
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 7 deletions.
35 changes: 35 additions & 0 deletions client/src/components/LiveTime.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// @flow

import React, { useEffect, useState } from 'react'
import cx from 'classnames'

const HOUR = 1000 * 60 * 60

/**
* A Component that self-updates evey hour.
*/
const LiveTime = ({ children, className, getDynamicClassName, ...props }) => {
const [dynamicChildren, setDynamicChildren] = useState(children())
const [dynamicClassName, setDynamicClassName] = useState(
getDynamicClassName ? getDynamicClassName() : undefined
)
useEffect(() => {
const updateComponent = () => {
setDynamicChildren(children())
if (getDynamicClassName) {
setDynamicClassName(getDynamicClassName())
}
}
const interval = setInterval(updateComponent, HOUR)
return () => clearInterval(interval)
}, [])
return (
<div
className={cx(className, dynamicClassName)}
children={dynamicChildren}
{...props}
/>
)
}

export default LiveTime
20 changes: 13 additions & 7 deletions client/src/components/Todos.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Table from 'components/Table'
import RouteLink from 'components/RouteLink'
import BookLink from 'components/BookLink'
import Button from 'components/Button'
import LiveTime from 'components/LiveTime'
import { TODOS_VIEW_URL } from 'utils/api'
import { todosActions } from 'store/actions'
import { todosCollection } from 'store/selectors'
Expand Down Expand Up @@ -54,17 +55,22 @@ export const SingleTodo = ({ todo, withRemoveButtons, shouldUpdateAll }) => {
/>
</span>
<div className='flex items-center'>
<div
<LiveTime
todo={todo}
title={todo.completed_on || todo.due_date}
className={cx('pr3', {
'light-red': !todo.is_completed && dueMoment.isBefore(),
blue: todo.is_completed,
})}
title={todo.completed_on || todo.due_date}
getDynamicClassName={() =>
cx({ 'light-red': !todo.is_completed && dueMoment.isBefore() })
}
>
{todo.completed_on
? `Completed on ${moment(todo.completed_on).format(DATE_FORMAT)}`
: dueMoment.fromNow()}
</div>
{() =>
todo.completed_on
? `Completed on ${moment(todo.completed_on).format(DATE_FORMAT)}`
: dueMoment.fromNow()
}
</LiveTime>
<Button
disabled={isDisabled}
onClick={toggleComplete(!todo.is_completed)}
Expand Down

0 comments on commit 2f640ef

Please sign in to comment.