# Apollo useQuery refetch cache
###### tags: `Apollo` `errorNote` `useQuery` `refetch`
> 使用 `useQuery` `refetch` network 回傳資料與實際 console.log 印出不一樣
> 哎呀,資料被 cache 住啦!
當進到某頁面使用 `useQuery` 取得第一次 data,執行刪除操作後使用 `refetch` 重新拉取 data
`uesQuery` 如下:
```
const {
data: myRoomList,
loading: listLdg,
refetch // 執行刪除操作後執行 refetch 重新拉取 data
} = useQuery(apiType.MY_ROOM_LIST, { variables });
```
卻發現畫面資料未更新,先來確認 Network 回傳的 data,可以看到 `userRooms` 總共 13 筆 (第一次 14筆)

再把 data 印出來發現還是原本的那 14 筆,QQ cache 住ㄌ

<br />
### 嘗試1: 加上 **`fetchPolicy: 'no-cache'`** > Nope! 沒用
(還不太確定為什麼不行)
```
const {
data: myRoomList,
loading: listLdg,
refetch // 執行刪除操作後執行 refetch 重新拉取 data
} = useQuery(apiType.MY_ROOM_LIST, { variables, fetchPolicy: 'no-cache' });
```
<br />
### 嘗試2: 使用 **`InMemoryCache`** 的 merge > Nope! 沒用
想說使用 merge 來比對 existing 及 incoming data, 然後回傳至邏輯,結果第一次取得會進 merge function, 但是使用 refetch 就不會跑進來,恩~
```
const createApolloClient = ({ onError }) => {
return new ApolloClient({
link: from([authMiddleware, createErrorLink(onError), splitLink]),
cache: new InMemoryCache({
typePolicies: {
ListUserInvitationResp: {
merge(existing, incoming) {
console.log('merge >>', existing, incoming);
return incoming;
}
},
ListUserRoomResp: {
merge(existing, incoming) {
console.log('merge >>', existing, incoming);
return incoming;
}
}
}
})
});
};
```
<br />
### 嘗試3: refetch 改用 fetchMore > Bingo!!
參考: [Refetch should not trigger a field merge](https://github.com/apollographql/apollo-client/issues/7491)
```
const {
data: myRoomList,
loading: listLdg,
// refetch
fetchMore
} = useQuery(apiType.MY_ROOM_LIST, { variables });
const refetchMyRoomList = async () => {
await fetchMore({ variables });
};
```
使用 `fetchMore` 需要帶入要搜尋的 `variables`
log 印出來的資料是最新的了,merge function 也有跑。
:::info
在參考文章裡有說到 refetch 應該不使用緩存機制 或是有什麼判斷至少能通過類似 merge function 以便處裡 data
等 v3.4 出來再看看改成怎麼樣 :slightly_smiling_face: