# Firebase v9 Realtime Database with React

토이프로젝트에 사용한 파이어베이스 관련 코드를 정리해보겠습니다. :tada:

## 파이어베이스 버전9. Realtime Database setup

#### 관련자료   &#x20;

* <https://firebase.google.com/docs/database/web/start>&#x20;
* <https://firebase.google.com/docs/database/web/read-and-write>&#x20;

### firebase docs 코드&#x20;

> Write data

```
import { getDatabase, ref, set } from "firebase/database";

function writeUserData(userId, name, email, imageUrl) {
  const db = getDatabase();
  set(ref(db, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}
```

> Read data

```
import { getDatabase, ref, onValue} from "firebase/database";

const db = getDatabase();
const starCountRef = ref(db, 'posts/' + postId + '/starCount');
onValue(starCountRef, (snapshot) => {
  const data = snapshot.val();
  updateStarCount(postElement, data);
});
```

### React Project에 적용하기

> service/card\_service.js

```
import firebaseApp from "./firebase";
import { getDatabase, ref, set, onValue, remove } from "firebase/database";

const database = getDatabase(firebaseApp);

export const saveCard = (userId, card, onUpdate) => {
  const url = `${userId}/cards/${card.id}`;
  set(ref(database, url), {
    ...card,
  });
  onUpdate(card);
};

export const deleteCard = (userId, card, onUpdate) => {
  const url = `${userId}/cards/${card.id}`;
  remove(ref(database, url));
  onUpdate(card);
};

export const syncCard = (userId, onUpdate) => {
  const url = `${userId}/cards`;
  const starCountRef = ref(database, url);
  onValue(starCountRef, (snapshot) => {
    const data = snapshot.val();
    data && onUpdate(data);
  });
};
```

코드 사용 예

```
import * as cardApi from "service/card_service"; 

cardApi.syncCard(userId, (cards) => {
  dispatch({ type: "SYNC", payload: cards });
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sharryhong.gitbook.io/front-end/front-end-dev/react/firebase-v9-realtime-database-with-react.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
