taiki-t's diary

React Native, Rails そして雑多な記録: The world is waiting for you to give it a meaning.

Relay: containerのinitialVariablesに値を渡す

追記: 2017/08/31 これはRelay Classicの時に書いたものです。

Introduction

非同期処理で何かごにょごにょした後、Relayにその値を使ってサーバーにリクエストを投げてほしかった。

やり方

Relay.createContainerを関数でラップする

雑な実装例:

componentDidMount() {
  this._asyncFunc()
}

async _asyncFunc() {
  try {
    let asyncVal = await someAsyncThings()
    this.setState({asyncVal})
  }
  catch (error) {
    console.log(error)
  }
}

render () {
  let component = null
  if (this.state.asyncVal) {
    component = (
      <Relay.RootContainer
        Component={createRelayComponent(this.state.asyncVal)}
        route={yourRoute}
        renderLoading={function() {
          return <div>Loading...</div>;
        }}
      />
    )
  } else {
    component = <div>Loading...</div>;
  }
  return component
}

function createRelayComponent(asyncVal) {
  return (
    Relay.createContainer(Component, { 
      initialVariables: {
        yourVar: asyncVal
      }

      fragments: { 
        ...
      }
    })
  )
}

参考リンク

Pass in React Component to Relay Variables and get a fragment from it. · Issue #775 · facebook/relay · GitHub

感想

他のやり方があれば教えほしい