# firebase CRUD를 위한 모듈
npm install firebase
# 난수 생성을 위한 모듈
npm install uid
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
apiKey: /* SDK 설정 및 구성 확인 */,
authDomain: /* */,
databaseURL: /* */,
projectId: /* */,
storageBucket: /* */,
messagingSenderId: /* */,
appId: /* */,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
//export default app;
export const db = getDatabase(app);
import React, { useState } from "react";
import { ref, set } from "firebase/database";
import { uid } from "uid";
import { db } from "./firebase";
function App() {
const [todo, setTodo] = useState("");
const handleTodoChange = e => {
setTodo(e.target.value);
};
// Write
const writeData = () => {
const uuid = uid();
set(ref(db, "test/" + uuid), {
todo,
uuid,
});
setTodo("");
};
return (
<div className="App">
<input type="text" value={todo} onChange={handleTodoChange}></input>
<button onClick={writeData}>Submit</button>
</div>
);
}
export default App;
// Read
import { ref, child, get } from "firebase/database";
import { db } from "./firebase";
// ...
const readOne = () => {
const dbRef = ref(db);
get(child(dbRef, "/test"))
.then(snapshot => {
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log("No data available");
}
})
.catch(error => {
console.error(error);
});
};
return (
//...
<button onClick={readOne}>read</button>
//...
)
import { update, ref } from "firebase/database";
import { db } from "./firebase";
// ...
// Update
const updateData = () => {
const 바꿀내용 = { todo };
return update(
ref(db, "/test/0e24bcf6769"),
바꿀내용
);
};
return (
//...
<button onClick={updateData}>update</button>
//...
)
import { remove, ref } from "firebase/database";
import { db } from "./firebase";
// ...
// Delete
const removeData = () => {
remove(ref(db, "/test/0e24bcf6769"));
};
return (
//...
<button onClick={removeData}>remove</button>
//...
)
고민해 볼 것들