swr-graphql icon indicating copy to clipboard operation
swr-graphql copied to clipboard

Optimistic UI: The user id is missing in the GraphQL mutation

Open arnaudbzn opened this issue 4 years ago • 2 comments

It prevents the GraphQL mutation to be effective because if the user id is required (and it should). Your example works as is if the user id is not required but the uuid is not stored in the database.

Existing code:

   const mutation = {
      'query': 'mutation users($name: String!) { insert_users(objects: [{name: $name}]) { affected_rows } }',
      'variables': { name: text}
    };

Suggested change:

    // mutate current data to optimistically update the UI
    var id = uuidv4();
    mutate(query, {users: [...data.users, {id, name: text}]}, false)
    // send text to the API
    const mutation = {
      'query': 'mutation users($id: String!, $name: String!) { insert_users(objects: [{id: $id, name: $name}]) { affected_rows } }',
      'variables': { id: id, name: text}
    };

arnaudbzn avatar Dec 14 '20 19:12 arnaudbzn

@arnaudbzn - Ideally the user id is automatically generated at the database layer. For example, using a default value like gen_random_uuid() or auto-incrementing integer should do the trick. Although the id column was intentionally used as text type to support external auth solutions like Auth0 or Firebase, we can fill in uuid to keep it simple.

I will make the default value change as part of the database schema and the blog post instead of changing the code here.

praveenweb avatar Dec 15 '20 07:12 praveenweb

@praveenweb - Sure, a uuid generated at the database layer seems to be the proper solution.

But you'd have to find a solution when calling mutate with the client-side generated id here:

    mutate(query, {users: [...data.users, {id: uuidv4(), name: text}]}, false)

You cannot have two different user id values (one generated client-side and the other one generated server-side).

arnaudbzn avatar Dec 15 '20 10:12 arnaudbzn