티스토리 뷰

react native

React Native Realm SDK 사용방법 , 설치법

YG - 96년생 , 강아지 있음, 개발자 희망 2022. 2. 19. 17:26

Realm

Realm 은 데이터를 휴대폰에 저장할 수 있는 MongoDB 와 AsyncStorage와 비슷한 역할을 하는 모바일 전용 라이브러리입니다.

 

설치 방법

npm install realm

 

 

Install Realm for React Native — MongoDB Realm

Docs Home → MongoDB RealmThe MongoDB Realm React Native SDK enables development of React Native applications using the JavaScript and TypeScript languages. React Native enables you to build cross-platform iOS and Android apps with a single codebase using

docs.mongodb.com

 

사용 방법

import Realm from "realm";

 

응용 프로그램의 개체 모델은 영역 데이터베이스에 저장할 수 있는 데이터를 정의합니다.

영역 객체 유형을 정의하려면 유형의 이름과 속성을 지정하는 스키마 객체를 작성합니다. 형식 이름은 영역의 개체 형식 중에서 고유해야 합니다. 특정 속성을 정의하는 방법에 대한 자세한 내용은 정의를 참조하십시오.

 

Schema 만들기

 

다음 코드는 작업 개체의 개체 모델을 정의하는 방법을 보여 줍니다. 이 예에서는 다음을 수행합니다.

 

  • primaryKey는 int 유형의 _id입니다 (기본 키에 사용되는 다른 일반적인 유형은 ObjectId입니다).
  • 이름 필드는 필수입니다.
  • 그 상태는 선택 사항이며 데이터 유형 바로 뒤에 물음표로 표시됩니다.

    const TaskSchema = {
      name: "Task",
      properties: {
        _id: "int",
        name: "string",
        status: "string?",
      },
      primaryKey: "_id",
    };​

 

Open a Realm

영역을 연 후에는 영역에 객체를 작성할 수 있습니다. 모든 쓰기는 쓰기 트랜잭션 내에서 이루어져야 합니다.

const realm = await Realm.open({
  path: "myrealm",
  schema: [TaskSchema],
});

 

 

  • path : 영역 데이터베이스가 저장된 파일의 경로.
  • schema optional : 이 영역의 모든 객체 유형을 지정합니다. 이 경로에 영역을 처음 만들 때 필요합니다. 생략하면 스키마가 기존 영역 파일에서 읽힙니다.

 

 

Class: Realm

Create a new Realm instance using the provided config. If a Realm does not yet exist at config.path (or Realm.defaultPath if not provided), then this constructor will create it with the provided config.schema (which is required in this case). Otherwise, th

docs.mongodb.com

Create Realm Objects

영역을 연 후에는 영역에 객체를 작성할 수 있습니다. 모든 쓰기는 쓰기 트랜잭션 내에서 이루어져야 합니다.

 

realm.write ()로 연후에 create로 하시면  됩니다.

// Add a couple of Tasks in a single, atomic transaction
let task1, task2;
realm.write(() => {
  task1 = realm.create("Task", {
    _id: 1,
    name: "go grocery shopping",
    status: "Open",
  });
  task2 = realm.create("Task", {
    _id: 2,
    name: "go exercise",
    status: "Open",
  });
  console.log(`created two tasks: ${task1.name} & ${task2.name}`);
});
// use task1 and task2

 

 

 

Find, Sort, and Filter Objects

 

다음 코드는 다음 방법을 보여줍니다.

 

  • 작업 개체 유형의 모든 인스턴스를 쿼리 합니다.
  • 쿼리를 필터링하여 "열린" 태스크만 검색합니다.
  • 이름을 기준으로 태스크를 오름차순으로 정렬합니다.

realm.objects("만든 schema이름")을 하면 찾을 수 있고 

 

realm을 이용해서 filter와 sort 또한 할 수 있습니다.

// query realm for all instances of the "Task" type.
const tasks = realm.objects("Task");
console.log(`The lists of tasks are: ${tasks.map((task) => task.name)}`);
// filter for all tasks with a status of "Open"
const openTasks = tasks.filtered("status = 'Open'");
console.log(
  `The lists of open tasks are: ${openTasks.map(
    (openTask) => openTask.name
  )}`
);
// Sort tasks by name in ascending order
const tasksByName = tasks.sorted("name");
console.log(
  `The lists of tasks in alphabetical order are: ${tasksByName.map(
    (taskByName) => taskByName.name
  )}`
);

 

실시간으로 realm 데이터 반영되게 하는 방법

useEffect를 사용하여 addListener와 removeAllListeners를 이용하면 realm을 활용해서 데이터를 추가할 때 실시간으로 데이터를 반영시킬 수 있습니다.

  const realm: any = useDB();
  const [feelings, setFeelings] = useState<feelingSchemaProps | any>([]);
  useEffect(() => {
    const feelings = realm.object('Feeling');
    setFeelings(feelings);
    feelings.addListener(() => {
      const feelings = realm.object('Feeling');
      setFeelings(feelings);
    });
    return () => {
      feelings.removeAllListeners();
    };
  }, []);

 

Watch for Changes

위의 실시간으로 데이터를 바뀌게 하는 것을 공식문서에서는 다음과 같이 권장하고 있습니다.

export function watch(realm) {
  // Query realm for all instances of the "Task" type.
  const tasks = realm.objects('Task');
  // Define the collection notification listener
  function listener(tasks, changes) {
    // Update UI in response to deleted objects
    changes.deletions.forEach(index => {
      // Deleted objects cannot be accessed directly,
      // but we can update a UI list, etc. knowing the index.
    });
    // Update UI in response to inserted objects
    changes.insertions.forEach(index => {
      let insertedTasks = tasks[index];
      // ...
    });
    // Update UI in response to modified objects
    changes.modifications.forEach(index => {
      let modifiedTask = tasks[index];
      // ...
    });
  }
  // Observe collection notifications.
  return tasks.addListener(listener);
}

 

그래서 아까 이 코드를

 

  const realm: any = useDB();
  const [feelings, setFeelings] = useState<feelingSchemaProps | any>([]);
  useEffect(() => {
    const feelings = realm.object('Feeling');
    setFeelings(feelings);
    feelings.addListener(() => {
      const feelings = realm.object('Feeling');
      setFeelings(feelings);
    });
    return () => {
      feelings.removeAllListeners();
    };
  }, []);

이렇게 단축해서 사용할 수 있습니다.

 

addListener 에는 2가지 인자를 받을 수 있고 2번째 인자인 changes 에는 다양한 함수 옵션들이 있습니다.

  const realm: any = useDB();
  const [feelings, setFeelings] = useState<feelingSchemaProps | any>([]);
  useEffect(() => {
    feelings.addListener((feelings, changes) => {
      setFeelings(feelings.sorted('_id', true));
    });
    return () => {
      feelings.removeAllListeners();
    };
  }, []);

 

https://docs.mongodb.com/realm/sdk/react-native/examples/use-change-listeners-in-components/

 

Use Change Listeners In Components - React Native SDK — MongoDB Realm

Docs Home → MongoDB RealmA best practice is to copy Realm objects to your component's state. However, since Realm objects are live and automatically update in response to changes, you must update the copies of them to prevent your UI from drifting out of

docs.mongodb.com

 

Find a Specific Object by Primary Key

지정된 개체의 기본 키를 알고 있으면 Realm.objectForPrimaryKey()를 사용하여 직접 확인할 수 있습니다.

 

const myTask = realm.objectForPrimaryKey("Task", 12342245); // search for a realm object with a primary key that is an int.

 

 

https://docs.mongodb.com/realm/sdk/react-native/examples/read-and-write-data/

 

Read & Write Data - React Native SDK — MongoDB Realm

Docs Home → MongoDB RealmThe examples on this page use the following schemas:const TaskSchema = { name: "Task", properties: { _id: "int", name: "string", priority: "int?", progressMinutes: "int?", }, primaryKey: "_id",};const PersonSchema = { name: "Pers

docs.mongodb.com

Delete Objects

데이터를 지우는 방법

 

realm.write(() => {
  // Delete the task from the realm.
  realm.delete(task);
  // Discard the reference.
  task = null;
});

 

 

주의사항 

Expo Go 앱에서는 사용할 수 없습니다.

다음과 같은 에러를 만나게 될 것입니다.

 

느낀 점

 

asyncStorage와 비교해서 좀 더 간편하고 속도가 빨랐던 것 같습니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함