2017-06-01 31 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()) 

第二種方法應該每次都有效。這並不完全樂觀,但會導致數據更新。