Last active
April 18, 2022 19:31
-
-
Save pearcircuitmike/ad93e5a97acc43e074ebc8106dfd0863 to your computer and use it in GitHub Desktop.
Not getting id from firebase UseCollections
This file contains 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 "../App.css"; | |
import {useState} from "react"; | |
import {auth, firestore} from "../firebase"; | |
import firebase from "../firebase"; | |
import {useCollectionData} from "react-firebase-hooks/firestore"; | |
const Todos = () => { | |
const [todo, setTodo] = useState(""); | |
const todosRef = firestore.collection(`users/${auth.currentUser.uid}/todos`); | |
const [todos] = useCollectionData(todosRef, { idField: "id" }); | |
const signOut = () => auth.signOut(); | |
const onSubmitTodo = (event) => { | |
event.preventDefault(); | |
setTodo(""); | |
todosRef.add({ | |
text: todo, | |
complete: false, | |
createdAt: firebase.firestore.FieldValue.serverTimestamp(), | |
}); | |
}; | |
return ( | |
<> | |
<header> | |
<button onClick = {signOut}>Sign Out</button> | |
</header> | |
<main> | |
<form onSubmit = {onSubmitTodo}> | |
<input | |
required | |
value = {todo} | |
onChange = {(e) => setTodo(e.target.value)} | |
placeholder="what's next?" | |
/> | |
<button type="submit"> Add </button> | |
</form> | |
{todos && todos.map((todo)=> <Todo key={todo.id} {...todo} />)} | |
</main> | |
</> | |
); | |
}; | |
const Todo = ({ id, complete, text}) => { | |
const todosRef = firestore.collection(`users/${auth.currentUser.uid}/todos`); | |
const onCompleteTodo = (id, complete) => | |
todosRef.doc(id).set({ complete: !complete }, { merge: true }); | |
const onDeleteTodo = (id) => todosRef.doc(id).delete(); | |
return ( | |
<div key={id} className="todo"> | |
<button | |
className={`todo-item ${complete ? "complete" : ""}`} | |
tabIndex="0" | |
onClick={()=> onCompleteTodo(id, complete)} | |
> | |
{text} | |
</button> | |
<button onClick={() => onDeleteTodo(id)}>x</button> | |
</div> | |
); | |
}; | |
export default Todos; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment