2
votes

I have the following Router and routes using the react-router-relay package

ReactDOM.render(
    <Router
        history={browserHistory}
        render={applyRouterMiddleware(useRelay)}
        environment={Relay.Store}
    >
            <Route
                path="/user/:userId"
                component={User}
                queries={StoreQueries}
            />   
    </Router>,
    document.getElementById('root')
);

My StoreType from GraphQL looks like the following, with the user field accepting an id argument representing a non-null integer:

let StoreType = new GraphQLObjectType({
    name: 'Store',
    fields: () => ({
        user: {
            type: UserType,
            args: {
                id: {
                    type: new GraphQLNonNull(GraphQLInt)
                }
            },
            resolve: (root, args) => db.user.findById(args.id)
        },
    })
})

My Relay container for the user/:userId route:

import React from 'react';
import Relay from 'react-relay'


class User extends React.Component {
    render () {
        return <div>
            User goes here!
        </div>;
    }
}

User = Relay.createContainer(User, {
    initialVariables: {
        userId: null,
    },

    fragments: {
        store: () => Relay.QL`
            fragment on Store {
                user(id: $userId) {
                    name
                }
            }
        `
    }
});

export default User;

When I visit /user/1 in the browser, react-router-relay treats :userId as a string from the route instead of an integer, and GraphQL returns the JSON-encoded error message "Argument \"id\" has invalid value \"1\".\nExpected type \"Int\", found \"1\"."

Is there any way to cast the userId argument passed in the URL to an integer? Or is there a custom GraphQL scalar type that supports well-formed numeric strings as well as integers? Any input or direction on this is appreciated.

1

1 Answers

1
votes

I faced with the same problem recently and ended up with this solution:

<Route
            path="/user/:userId"
            component={User}
            queries={StoreQueries}
            prepareParams={({userId}) => ({userId: parseInt(userId, 10)})}/>
        />