6
votes

In the following code, what's the best way to pass the database variable as props to all the components served by the Router/NavigationProvider?

import {
  createRouter,
  NavigationProvider,
  StackNavigation,
} from '@exponent/ex-navigation'

const Router = createRouter(() => ({
  jobs: () => Jobs,
  sample: () => Sample
}))

render () {
  const database = this.openDatabase()
  <NavigationProvider router={Router}>
        <StackNavigation initialRoute={Router.getRoute('home')} />
  </NavigationProvider>
}

Thanks!

1
have you solved this in a manner way? I'm trying to achieve the same thing with ex-navigation component . Would help if you could share some snippets.el.severo
The accepted answer solved it for me in this instance. Just create a file (services/database.js) and import the db instance when you need itcmrichards
@chrichards: I see, thanks!el.severo

1 Answers

-1
votes

You should create a new javascript file which exports your database connection and import it in your component you wish to use it.

You can also create higher order component which gives database connection as a prop to your component. This is similar to withNavigation which is built-in in ExNavigation or connect which comes with Redux's React bindings.

However, since HOC is a bit advanced topic (but not hard to grasp!) here is an example without it.

services/database.js

// Open database connection here and export it like any other module.
// The following is pseudo code to illustrate example

import { database } from 'database'
export default database.connect()

routes.js

import Jobs from './containers/Jobs'
import Sample from './containers/Sample'
import { createRouter } from '@exponent/ex-navigation'

const Router = createRouter(() => ({
  jobs: () => Jobs,
  sample: () => Sample
}))

export default Router

App.js

import React from 'react'
import {
  NavigationProvider,
  StackNavigation,
} from '@exponent/ex-navigation'

const App = () => (
  <NavigationProvider router={Router}>
     <StackNavigation initialRoute={Router.getRoute('home')} />
  </NavigationProvider>
)

export default App

containers/Jobs.js

import React, { Component } from 'react'

// Import database connection in every container component you wish to use it
import databaseConnection from '../services/database'

export default class Jobs extends Component {
  state = {
    jobs: []
  }

  componentDidMount() {
    databaseConnection
      .get('jobs')
      .then(jobs => this.setState({ jobs }))
  }

  render() {
    return (
      {this.state.jobs.map(job =>
        // Render jobs
      )}
    )
  }
}