Search code examples
javascriptreact-nativerealm

Use another file for realm queries in React-Native


Im new to React-Native and Im using Realm as my database. Im trying to create a class which holds all my realm queries and I will use it in my components. Today.js and Queries.js are on the same folder. I have this on my Today.js

import Queries from './Queries'
componentDidMount() {
   this._isMounted = true;
   let a = Queries.getAllExpenses();
}

and this is what I have on my Queries.js.

import Realm from 'realm'
let realm = new Realm({
schema: 
[
    {
    name: 'Expenses', 
    properties: 
        {
            id: 'int',
            value: 'int', 
            category: 'string', 
            description: 'string', 
            date: 'string', 
        }
    },
    {
    name: 'Categories', 
    properties: 
        { 
            id: 'int',
            name: 'string',
        }
    },
]
})

export default class Queries {
getAllExpenses() {
    let data = realm.objects('Expenses');
    let allExpenses = [];
    let i=0;
    for (; i <= data.length; i++) {
      allExpenses.push(data[i]);
    }
    return allExpenses;
}
getAllCategories() {
    return realm.objects('Categories');
};
}

Im getting the error undefined is not a function (evaluating '_Queries2.default.getAllExpenses()') Am I doing this wrong? I would be really glad for your help.


Solution

  • It looks like you are trying to call the getAllExpenses method directly on the class, not on an instance of the class.

    You should either change your export statement to instantiate the class: export default new Queries (and move the class definition itself above the export statement), or you could mark your methods as static if you want to use your class more like a namespace.