2017-06-01 55 views
1

发生突变后,用户界面不会使用新添加的项目进行更新,直到页面刷新。我怀疑问题出在突变的更新部分,但我不确定如何进一步排除故障。任何意见非常感谢。乐观的用户界面不更新 - 阿波罗

查询(单独的文件)

//List.js 

export const AllItemsQuery = gql` 
    query AllItemsQuery { 
    allItems { 
     id, 
     name, 
     type, 
     room 
     } 
    } 
`; 

突变

import {AllItemsQuery} from './List' 

const AddItemWithMutation = graphql(createItemMutation, { 
    props: ({ownProps, mutate}) => ({ 
     createItem: ({name, type, room}) => 
      mutate({ 
       variables: {name, type, room}, 
       optimisticResponse: { 
        __typename: 'Mutation', 
        createItem: { 
         __typename: 'Item', 
         name, 
         type, 
         room 
        }, 
       }, 
       update: (store, { data: { submitItem } }) => { 
        // Read the data from the cache for this query. 
        const data = store.readQuery({ query: AllItemsQuery }); 
        // Add the item from the mutation to the end. 
        data.allItems.push(submitItem); 
        // Write the data back to the cache. 
        store.writeQuery({ query: AllItemsQuery, data }); 
       } 
      }), 
    }), 
})(AddItem); 

回答

0

看起来有前途的,一件事是错的是突变data: { submitItem }结果的名称。因为在乐观回应中你声明它为createItem。你有没有console.log,这个变异是怎么样的?

update: (store, { 
 
    data: { 
 
    submitItem // should be createItem 
 
    } 
 
}) => { 
 
    // Read the data from our cache for this query. 
 
    const data = store.readQuery({ 
 
    query: AllItemsQuery 
 
    }); 
 
    // Add our comment from the mutation to the end. 
 
    data.allItems.push(submitItem); // also here 
 
    // Write our data back to the cache. 
 
    store.writeQuery({ 
 
    query: AllItemsQuery, 
 
    data 
 
    }); 
 
}

+0

感谢您的回答。这是一个好点,但它仍然没有给出预期的结果。使用开发工具插件,我可以看到它看起来不像商店正在更新。我真的不知道我可以在哪里寻找,但建议是受欢迎的。 – muninn9

0

我不能完全肯定,问题是你有以上的optimisticResponse功能(这是正确的做法),但我猜你用错误的返回值。例如,下面是我们使用的一个回应:

optimisticResponse: { 
    __typename: 'Mutation', 
    updateThing: { 
    __typename: 'Thing', 
    thing: result, 
    }, 
}, 

所以,如果我不得不采取胡乱猜测,我会说,你可能需要使用您的返回值中的类型尝试:

optimisticResponse: { 
    __typename: 'Mutation', 
    createItem: { 
     __typename: 'Item', 
     item: { // This was updated 
      name, 
      type, 
      room 
     } 
    }, 
}, 

作为替代方案,您可以只需refetch。在我们的代码库中有很多次,事情并没有按照我们想要的方式更新,我们也无法弄清楚为什么我们只是在突变解决后进行踢球并重新获取(突变返回一个承诺!)。例如:

this.props.createItem({ 
    ... // variables go here 
}).then(() => this.props.data.refetch()) 

第二种方法应该每次都有效。这并不完全乐观,但会导致数据更新。