Skip to content

Instantly share code, notes, and snippets.

@BaylorRae
Created January 27, 2020 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BaylorRae/2050fce4a5293fe2448299bcadffd192 to your computer and use it in GitHub Desktop.
Save BaylorRae/2050fce4a5293fe2448299bcadffd192 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react';
import './App.css';
import { firebase } from './config'
function useTimesList(sortDirection='asc') {
const [times, setTimes] = useState([])
useEffect(() => {
const unsubscribe = firebase
.firestore()
.collection('times')
.orderBy("time_seconds", sortDirection)
.onSnapshot((snapshot) => {
const newTimes = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data()
}))
setTimes(newTimes)
})
return () => unsubscribe()
}, [sortDirection])
return times
}
function TimesList() {
const [sortBy, setSortBy] = useState("asc")
const times = useTimesList(sortBy)
return (
<div>
<div>
Sort By:
<select value={sortBy} onChange={e => setSortBy(e.currentTarget.value)}>
<option value="asc">Time (Fastest First)</option>
<option value="desc">Time (Slowest First)</option>
</select>
</div>
<ol>
{times.map(time => <li key={time.id}>{time.title} - <code>{time.time_seconds} seconds</code></li>)}
</ol>
</div>
)
}
function NewTimeForm() {
const [title, setTitle] = useState('')
const [time, setTime] = useState('')
function addTime(e) {
e.preventDefault()
firebase
.firestore()
.collection("times")
.add({
title,
time_seconds: parseInt(time)
})
.then(() => {
setTitle('')
setTime('')
})
}
return (
<form onSubmit={addTime}>
<div>
<label>Title</label>
<input type="text" onChange={e => setTitle(e.currentTarget.value)} value={title} />
</div>
<div>
<label>Time (in seconds)</label>
<input type="number" onChange={e => setTime(e.currentTarget.value)} value={time} />
</div>
<button>Add Time</button>
</form>
)
}
function App() {
return (
<div className="App">
<h1>Just Clock It</h1>
<TimesList />
<NewTimeForm />
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment