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!
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.
To upsert an object, call Realm. create() with the update mode set to modified .
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With