Learn the process of storing data using Realm database in JavaScript

Recently, I started working with react-native and decided to incorporate realm database into my application. My goal is to pre-populate the data using a JSON file. Initially, I attempted to achieve this by utilizing the componentDidMount() function along with a for loop for data insertion. If anyone has any advice or guidance on this matter, it would be greatly appreciated.

Below is the code snippet I have written:

// Schema File:

import booksdata from './books.json';

const Realm = require('realm');

const BooksSchema = {
    name: 'Books',
    primaryKey: 'id',
    properties: {
        id: 'int', // primary key
        name: 'string',
        author: 'string',
        publisher: 'string',
    },
};

const databaseSchema = {
    path: 'books.realm',
    schema: [BooksSchema],
    schemaVersion: 0, // optional
};

export const mountData = () => new Promise((resolve, reject) => {
    Realm.open(databaseSchema)
        .then((realm) => {
            // Create Realm objects and write to local storage
            realm.write(() => {
                booksdata.forEach(obj => realm.create(databaseSchema, {
                    id: Math.floor(Date.now() / 1000),
                    name: obj.name,
                    author: obj.author,
                    publisher: obj.publisher,
                }));
            });
        });
});

// In the index file, I call componentDidMount :

 componentDidMount() {
    mountData().then().catch((error) => {
      alert(`Insert error ${error}`);
    });
  }

// However, I am encountering the following warning:

Possible Unhandled Promise Rejection (id: 0):
Error: objectType must be of type 'string', got ([object Object])
Error: objectType must be of type 'string', got ([object Object])
    at sendRequest (blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:62352:45)
    at sendRequest (blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:62385:24)
    at Object.callMethod (blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:62128:22)
    at Realm.<anonymous> (blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:61983:28)
    at blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:61408:15
    at tryCallOne (blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:16056:14)
    at blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:16157:17
    at blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:2884:21
    at _callTimer (blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:2773:9)
    at _callImmediatesPass (blob:http://localhost:8081/d198fbe8-8b32-4037-93a7-df5a46af4f15:2809:9)

Answer №1

To turn your JSON data into JavaScript objects, it's important that the objects align with your predetermined schema.

let parsedObjects = JSON.parse(data);
realm.write(() => {
    parsedObjects.forEach((object) => realm.create('data', object));
}

Here, 'data' represents the designated schema name.

Answer №2

Hey everyone, I just wanted to share my solution with you all! It turns out I was making a silly mistake in my code. When trying to insert a record into the realm, I forgot to specify the name of my schema. Instead of using databaseSchema, I should have passed BooksSchema.name (Books) as the schema name.

export const loadData = () => new Promise((resolve, reject) => {
    Realm.open(databaseSchema)
        .then((realm) => {
            // Create Realm objects and save to local storage
            realm.write(() => {
                booksdata.forEach(obj => realm.create(BooksSchema.name, {
                    id: Math.floor(Date.now() / 1000),
                    name: obj.name,
                    author: obj.author,
                    publisher: obj.publisher,
                }));
            });
        });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

Sorting list items using jQuery works seamlessly in modern browsers and IE7, however, it encounters issues specifically in IE9

Seems like there might be an issue here. It's not functioning properly in IE9. Could it be that IE9 doesn't handle JavaScript as expected? It's working fine in Chrome, FF, Safari, and even in IE7 (I verified this myself). If you want to tak ...

Error: Unable to locate the reference

Having trouble with my JavaScript code not recognizing the linked .js files I added. I initially linked them through CodePen, but manual references don't seem to be working. Attempted suggestions from this page Why does jQuery or a DOM method such as ...

Steps for deactivating a textbox upon checkbox activation

When I try to implement the instructions from the textbook, I'm encountering an issue where clicking on the checkbox doesn't disable the textbox on my website. <form action="#"> Billing Address same as Shipping Address: <input ...

Conceal or reveal radio buttons according to information in a table

How can I dynamically add and remove values from a table based on radio button selections? My goal is to add the selected value to the table and hide it from the radio button list, and if the value is deleted from the table, I want to show it back in the r ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

Is the XPath in Selenium executed against the Document Object Model (DOM) or the HTML file

Currently, I am in the process of developing a library for analyzing webpages. My approach involves using Selenium to access elements on a webpage through xpath. I have been contemplating replacing Selenium with an offline xpath tool. However, upon furthe ...

Executing PHP script simultaneously in the background with jQuery

I have a PHP script that performs time-consuming tasks in the background. All I want is to display a simple message to the user: "Command executed. Invites pending." The rest of the processing will happen behind the scenes in my .php file. I'm consid ...

The function element.checked = true/false in Vanilla Javascript seems to be malfunctioning

Here is the HTML code I am working with: <ul class="nav md-pills pills-default flex-column" role="tablist"> <li class="nav-item"> <input type="radio" name="q01" value="1" hidden checked> <a class="nav-link choice01 ...

Using the .load() function to import an HTML file from the directory above

I am trying to achieve the following structure: folder1 index folder2 page to load Can I dynamically load the 'page to load' in a div within the 'index' page using DIV.load()? I have attempted various paths (../folder2/page, ./, ...

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...

Unable to replicate the exact Bootstrap template found on their website

Attempting to replicate a template from bootstrap.com, but encountering issues with the copied version. The navigation bar is turning white instead of remaining black, and I'm unable to change the color. Additionally, facing problems with the toggle ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...

Navigate to a different component within Angular

Is there a way in Angular to scroll to a component using a button placed in another component? Below is the code snippet for the first component: <div id='banner' class="col-5 offset-1 d-flex justify-content-center align-items-cen ...

What could be causing JavaScript's wrapInner function to throw an error?

Somehow, the Firefox add-on I've been working on isn't functioning as expected. The initial line of code is executing without issues, which wraps content in a div element with an id of 'content_cont'. However, any subsequent lines of co ...

MongoDBError: Unauthorized access attempt for [action] operation by the user is prohibited

I've been struggling with this error for quite some time now, attempting all the recommendations on this forum without success. My goal is to develop a website where users can register and their credentials are saved in a database. Below is a snippet ...

Error encountered: TypeError: Unable to access attributes of null object (attempting to read 'useMemo')

In the development of a public component titled rc-component version0.1.14, I built a platform that allows for the sharing of common React pages amongst various projects. However, upon attempting to utilize this component in my project, I encountered the f ...

Does Node Express call the next middleware immediately when the next function is called?

Can someone please help me grasp the concept of how the next function operates within the Node Express framework? I know that we utilize the next function within the current middleware to trigger the execution of the subsequent middleware listed. These mid ...

Different methods to obscure solely URLs in AngularJS

Is there a way to effectively obfuscate URLs in AngularJS? Currently, I am using base 64 encoding as a method of obscuring my URLs. For example, let's say my URL is: I encode and decode it like this: aHR0cDovLzE5Mi4wLjAuMC9teS91cmwv However, when ...

Unable to verify password against NodeJS hash Passport

I am working on creating a function that will allow users to change their password. The first step is to compare the old password with the user's current password in the database. I have written code for this inside the router function, but it doesn&a ...