My data on my To-Do app will not show up in the Firestore Database. I get a warning in the terminal that reads "WARNING in src/components/AddTodo.js Line 3:10: 'collection' is defined but never used no-unused-vars"
In the console it also reads Uncaught (in promise) TypeError: firebase__WEBPACK_IMPORTED_MODULE_1_.db.collection is not a function.
AddToDo.JS
import React from 'react';
import { db } from '../firebase';
import { collection, addDoc } from 'firebase/firestore';
export default function AddTodo() {
const [title, setTitle] = React.useState('');
const handleSubmit = async (e) => {
e.preventDefault();
if (title !== '') {
await addDoc(db.collection('todos'), { //<----Problem???--->//
title,
completed: false,
});
setTitle('');
}
};
return (
<form onSubmit={handleSubmit}>
<div className="input_container">
<input
type="text"
placeholder="Enter todo..."
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className="btn_container">
<button>Add</button>
</div>
</form>
);
}
App.js
import './App.css';
import React from 'react';
import Title from './components/Title';
import AddTodo from './components/AddTodo';
function App() {
return (
<div className="App">
<div>
<Title />
</div>
<div>
<AddTodo />
</div>
</div>
);
}
export default App;
Firebase.js
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
//Firebase configuration
const firebaseConfig = {
apiKey: 'AIzaSyCqranC2Lg9HXqoPPVAB3BVQqJFMAi569E',
authDomain: 'fir-todo-ee3df.firebaseapp.com',
projectId: 'fir-todo-ee3df',
storageBucket: 'fir-todo-ee3df.appspot.com',
messagingSenderId: '861076554800',
appId: '1:861076554800:web:070895ff68a12d187f99f5',
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };
Title.js
import React from 'react';
export default function Title() {
return (
<div className="title">
<h1>Todo App</h1>
</div>
);
}
I figured out my own answer. This was a matter of syntax since Firebase updated to the latest SDK version. Line 11 should read as await addDoc(collection(db, 'todos'), {
It seems you are using v9 (modular) of firebase.
Try using this code:
await addDoc(collection(db, 'todos'), {
title,
completed: false,
});
You can check the firebase documentation for more information on how to add new documents.