4

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 Answer 1

1

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)})}/>
        /> 
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I wound up doing. Is this still the best solution in v4? Kinda sucks…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.