Mr Davros
Mr Davros

Reputation: 98

How can I pass a URL querystring variable dynamically to a composed graphql query in react?

I am attempting to build a component using date from a graphql query but cannot see how dynamically supply a variable if it is not available in props when my component is created. eg. I have:-

class UsageComponent extends Component {
    render() {
        const params = this.queryStringParse(window.location.href);
        const queryStringImageId = params.id;

        const imageDetailsResults = this.props.getImageDetails.imageByImageId

        (etc...)
    }
}



const GET_IMAGE_DETAILS_QUERY = gql`
    query getImageDetails($imageId: Int!){
        imageByImageId(imageId:$imageId) {
            filename
            originalFilename
            width
            height
            description
            (etc...)
        }
    }
`;


export default compose(
        graphql(GET_IMAGE_DETAILS_QUERY, {name: "getImageDetails", options: props => { return { variables: { imageId: 123456 }}; }}),
        graphql(GET_PUBLICATIONS_QUERY, {name: "getPublications"})
)(ImageBrowser);

Which works fine. i.e. imageDetailsResults is populated and I can use the data subsequently in the render function.

However I would like to be able to replace that hard set "imageId: 123456" in the composed graphql with the queryStringImageId value I get in the component render.

I don't think I am able to set this a props value as I'm coming to this component page from a redirected url:-

<Switch>
    <AuthRoute path="/image" component={ImageBrowser} token={token} />
</Switch>

Any suggestions would be much appreciated!

Upvotes: 0

Views: 1941

Answers (1)

xadm
xadm

Reputation: 8418

You're probably looking for a method to use urls like /image/123456.

With react-router-dom you can define route with param:

    <AuthRoute path="/image/:id" component={ImageBrowser} token={token} />

This way component gets router's prop passed in, match.params.id in this case ... and we're only one step away from final param passing:

export default compose(
    graphql(GET_IMAGE_DETAILS_QUERY, {
      name: "getImageDetails", 
      options: props => { 
        return { variables: { imageId: props.match.params.id }};
      }}),
    graphql(GET_PUBLICATIONS_QUERY, {name: "getPublications"})
)(ImageBrowser);

Upvotes: 1

Related Questions