How to Pass Watermelon DB react native from APP to component

3.1k views Asked by At

Thanks in advance Am currently using watermelon DB and I have configured it as per the documentation. How to I pass database from index.js to my component

index.js

 import { AppRegistry } from 'react-native';
    import {App} from './App';
    import { name as appName } from './app.json';        
    import { Database } from "@nozbe/watermelondb";
    import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite";
    import { dbModel } from "./src/model"
    import { mySchema } from "./src/model/schema"  
    const adapter = new SQLiteAdapter({
    dbName: "myDB",
    schema: mySchema 
    });            
    const database = new Database({
    adapter,
    modelClasses: [dbModel],
    actionsEnabled: true,
    });
    AppRegistry.registerComponent(appName,  () => App);

App.js

import * as React from 'react';
import { Provider } from 'react-redux';
import { AppWithSidebar } from './src/components';
import configureStore from './src/store/configureStore';

const store = configureStore();

export default () => (
  <Provider store={store} >
    <AppWithMenu/> 
  </Provider >
);

And In App.js I have my Route and its component. How I pass the database from the index.js to my component screen. I also need to pass it in my route to component screen and my route look like

 <Route path="/mytable" component={TableScreen} />
2

There are 2 answers

1
hong developer On BEST ANSWER

You can try to solve this problem by importing.

index.js

  export const adapter = new SQLiteAdapter({
    dbName: "myDB",
    schema: mySchema 
    });   
  export const database = new Database({
    adapter,
    modelClasses: [dbModel],
    actionsEnabled: true,
    });

mytable.js

import { database } from "index file path" // ex) '../../index.js'
database.collections
0
Oleg Kupriianov On

You could use same logic as you are doing with redux.

import DatabaseProvider from '@nozbe/watermelondb/DatabaseProvider';
import { Database } from "@nozbe/watermelondb";
import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite";

const adapter = new SQLiteAdapter({
    dbName: "myDB",
    schema: mySchema 
    });            
const database = new Database({
    adapter,
    modelClasses: [dbModel],
    actionsEnabled: true,
    });

   <DatabaseProvider database={database}>
    <Provider store={store} >
      <AppWithMenu/> 
    </Provider >
   </DatabaseProvider>

then use hook in any of your wrapped components like:

    import { useDatabase } from '@nozbe/watermelondb/hooks';

    const WrappedComponent = () => {
    const database = useDatabase();
    ...etc
    }