Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fast insert a JSON into Realm Database for a React Native App

I'm designing an offline app using React Native and Realm. One of the features is downloading data from the web API before going offline.The downloaded data is a long JSON. For example:

[{"EventID":"3769","EventName":"Birthday Party","EventDate":"Jun 21 2018  4:00 PM"},{"EventID":"4232","EventName":"Homecoming","EventDate":"Jun 22 2018 11:00 PM"}, {"EventID":"3838","EventName":"the Summer Show","EventDate":"Jun 28 2018  2:00 AM"}]

There are many examples of how to insert one entry in Realm, such as:

realm.write(() => {
  Event.push({EventID: 3769, EventName: 'Birthday Party'});
  Event.push({EventID: 4232, EventName: 'Homecoming'});
});

But is there a way to bulk insert JSON into a Realm table at once?

Many thanks!!!


Update - Works!

I've tried geisshirt's solution (thanks!) with codes below. It takes about 10sec to import a JSON String with 50,000 entities. (Each entity has ID, name and date properties). One trick is that debug mode is much slower than running on the real app.

React Native Code:

axios.get('https://APISERVER/XX/GET_EVENTS')
 .then(response => {
   Realm.open({
     schema: [{ name: 'Events', properties: { EventID: 'string', EventName: 'string', EventDate: 'string' } }]
   }).then(realm => {
     realm.write(() => {
        response.data.forEach(obj => {
            realm.create('Events', obj);
        });
    });
 })

Thanks again!

like image 710
yzhou5 Avatar asked Jun 19 '18 21:06

yzhou5


People also ask

How fetch data from JSON API in react native?

In React Native, you can request data from an API over the network using the fetch() method. We are creating a function called getUsers, where we will fetch json data from rest api. We want to fetch the data as soon as the component mounts, so calling getUsers function in useEffect hook.

How do you update realm objects in react native?

To upsert an object, call Realm. create() with the update mode set to modified .


1 Answers

You can do something like:

let objs = JSON.parse('[{"EventID":"3769","EventName":"Birthday Party","EventDate":"Jun 21 2018  4:00 PM"},{"EventID":"4232","EventName":"Homecoming","EventDate":"Jun 22 2018 11:00 PM"}, {"EventID":"3838","EventName":"the Summer Show","EventDate":"Jun 28 2018  2:00 AM"}]');
realm.write(() => {
    objs.forEach(obj => {
        realm.create('Event', obj);
    });
});

You insert all object in one transaction (realm.write()).

like image 115
geisshirt Avatar answered Oct 01 '22 11:10

geisshirt