6

I have a simple react component that must load data from server when user ask it. Problem is that i don't know how to transfer dynamic variable speakerUrl and access it in before component load state. Sure i can access it from this.props.params, but component is not loaded and i can't access it when i make a graphql query. Query - QuerySpeaker is working fine when i manualy set url variable.

Router

<Route path="/speaker/:speakerUrl" component={SpeakerPage} />

Component - SpeakerPage

import React from 'react';
import { graphql } from 'react-apollo';

import { QuerySpeaker } from '../redux/graphql/querys';

class SpeakerPage extends React.Component {
    render( ) {
        console.log( this.props );
        return (
            <div className="ui container">
                <div className="ui grid">
                    <div className="row">
                        Hello
                    </div>
                </div>
            </div>
        )
    }
}

export default graphql(QuerySpeaker, {
     options: ({ url }) => ({ variables: { url } }) <- here is my problem, how can i set this url variable?
})( SpeakerPage );
SLI
  • 713
  • 11
  • 29

1 Answers1

18

Based on the react-apollo documentation, the argument passed to the options function is the props object passed to the component. When react-router renders your component, it passes it the params as a prop. That means that params should be a property of the object passed to the options function.

export default graphql(QuerySpeaker, {
  options: (props) => ({ variables: { url: props.match.params.speakerUrl } })
})( SpeakerPage );
Paul S
  • 35,097
  • 6
  • 41
  • 38
  • 1
    Not very obvious in the docs considering how frequent this use case comes up in dev. Thank you! – mattdlockyer Mar 29 '17 at 16:26
  • Thank you Paul. I resolved a similar problem I had! Upvote from me. – nik_m Jul 12 '17 at 14:18
  • In think that in react router v4, you should use the match property: props.match.params.speakerUrl – yonih Aug 05 '17 at 13:08
  • 1
    @yonih Yes, you're right. I wrote this while v4 was still in beta (or maybe alpha) and I believe that the API was slightly different at the time. Will update my answer. – Paul S Aug 05 '17 at 18:15