Created
January 27, 2020 22:54
-
-
Save BaylorRae/2050fce4a5293fe2448299bcadffd192 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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