j.Doe
j.Doe

Reputation: 212

Fetch Data from WatermelonDB in React

I am using WatermelonDB as a local database of my app. I have a method getPlaces() inside a class AccessDB:

static async getPlaces() {
        const postsCollection = database.collections.get('places');
        const allPosts = await postsCollection.query().fetch();
        return allPosts;
}

Calling getPlaces() using AccessDB.getPlaces() with async and await works. How can I fetch the results matching the query?

Upvotes: 4

Views: 2586

Answers (2)

TheRuedi
TheRuedi

Reputation: 132

The variable allPosts is an array with all places in your case. So to access the properties of the places, you would do in a different class:

import AccessDB from './AccessDB';

and then somewhere for example

(async () => {
    try {
        const places = await AccessDB.getPlaces();

        var buffer = '';
        for (place in places) {
            buffer += places[place].name + '\n'
        }
        console.log(buffer)
    } catch(e) {console.log(e)}
})()

You have to be carefully when debugging with console.log, as

1) console.log skips outputs if executed fast one after the other, e.g. if you console.log the places[place].name every time in the for-loop above and

2) if you console.log(places) you see the same as if you console.log(database) which is very confusing. You would expect to see [Object object],[Object object]..., which you see when you use alert(places).

Upvotes: 1

Talgat Saribayev
Talgat Saribayev

Reputation: 1938

Maybe I am not understanding fully. But did you try to put query inside your query method

const allPosts = await postsCollection.query(Q.where('is_verified', true)).fetch();

Also do not forget that getPlaces is async and your need async\await to get return data.

Upvotes: 0

Related Questions