WatermelonDB
WatermelonDB copied to clipboard
withObservables not working
I have schema, model and instance database.
User Model:
// User Model
// @flow
import { Model } from '@nozbe/watermelondb'
import { field, json, } from '@nozbe/watermelondb/decorators'
import { Tables, Columns } from './Schema.js'
const Column = Columns.users
const sanitizeBody = json => json
export default class User extends Model {
static table = Tables.users
@json(Column.body, sanitizeBody)
body: string
@field(Column.token)
token: string
async addUser (body: string, token: string) {
const result = await this.collections.get('users').create(user => {
user.body = body
user.token = token
})
return result
}
async destroyPermanently () {
await this.users.destroyAllPermanently()
}
}
My Schema:
// Schema
// @flow
import {
tableName,
columnName,
type TableName,
appSchema,
tableSchema,
} from '@nozbe/watermelondb'
import type User from './User.js'
export const Tables = {
users: (tableName('users'): TableName<User>),
}
export const Columns = {
users: {
body: columnName('body'),
token: columnName('token'),
},
}
export const UserSchema = appSchema({
version: 1,
tables: [
tableSchema({
name: Tables.users,
columns: [
{ name: Columns.users.body, type: 'string' },
{ name: Columns.users.token, type: 'string' },
],
}),
// ...
],
})
and called it
// @flow
import { Database } from '@nozbe/watermelondb'
import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite'
import User from './User'
import { UserSchema } from './Schema'
const adapter = new SQLiteAdapter({
dbName: 'Oootopia', // ⬅️ Give your database a name!
schema: UserSchema,
})
const database = new Database({
adapter,
modelClasses: [User],
})
export default database
But when i tried to integrate withObservables i got an error.

My component is like
// class Auth
// ...
const enhance = withObservables(['user'], props => {
console.log('props', props)
return {
user: props.user.body.observe(),
}
})
const EnhancedAuth = enhance(Auth)
export default EnhancedAuth
it seems user is undefined, but I am not really sure what a missing. I hope there is a solution to this problem.
Edit: it works if i called via promise
await db.collections.get('users').find(id)
thank you so much.
@ikhsanalatsary You try to observe user.body which is actually @json field, not an observable. You need to observe model instead:
class Auth extends Component {
render() {
const body = this.props.user.body
// do sth with body
}
}
const enhance = withObservables(['user'], props => {
console.log('props', props)
return {
user: props.user.observe(),
}
})
I assume there is a user in the database and you've provided it as prop into EnhancedAuth component.
const user = await db.collections.get('users').find(id)
<EnhancedAuth user={user} />
ok, got it. thank you so much @rkrajewski