也许我误解了这个包的功能,但我认为它会读取缓存的响应并帮助完成脱机应用程序的功能。
import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
export const DATA_QUERY = gql`
query Data {
me {
name
bestFriend {
name
}
}
}
`
const options = () => ({
fetchPolicy: 'cache-only'
})
const withData = graphql(DATA_QUERY, { options })
export const Start = ({ data }) =>
data.loading ? (
'loading!'
) : data.me ? (
<div>
{console.log('data', data)}
<h3>Me: {data.me.name}</h3>
<p>Best friend: {data.me.bestFriend.name}</p>
</div>
) : (
'no data'
)
export default withData(Start)
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { ApolloProvider } from 'react-apollo'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { persistCache } from 'apollo-cache-persist'
const cache = new InMemoryCache()
persistCache({
cache,
storage: window.localStorage,
debug: true
})
export const client = new ApolloClient({
link: new HttpLink({ uri: 'https://v9zqq45l3.lp.gql.zone/graphql' }),
cache
})
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root'));
registerServiceWorker();
我的localStorage中有缓存
apollo-cache-persist: "{"$ROOT_QUERY.me":{"name":"Bob","bestFriend":{"type":"id","id`enter code here`":"$ROOT_QUERY.me.bestFriend","generated":true}"
使用fetchPolicy运行上述示例时:'cache-only'组件呈现'无数据'。如果我执行默认的fetchPolicy,cache-first,那么我得到预期的结果,但我可以看到正在进行网络请求。
编辑:现在使用Daniels答案,此解决方法等待在运行查询之前恢复缓存。
import Start from './Start'
class App extends Component {
state = {
show: false
}
toggle = () =>
this.setState({ show: !this.state.show })
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<br/><br/>
<button onClick={this.toggle}>Show it</button>
<br/><br/>
{this.state.show && <Start />}
</div>
);
}
}
答案 0 :(得分:1)
为了正确缓存并稍后从缓存中检索数据,Apollo需要使用id
(或_id
)。如果要使用不同的属性作为id(如name
),可以将dataIdFromObject函数传递给内存缓存的配置:
const cache = new InMemoryCache({
dataIdFromObject: object => {
switch (object.__typename) {
//User is whatever type "me" query resolves to
case 'User': return object.name;
default: return object.id || object._id;
}
}
});
答案 1 :(得分:0)
这样的东西有效,但我想知道是否应该有一个更优雅的解决方案。也许是重试链接。
https://github.com/apollographql/apollo-cache-persist/issues?utf8=%E2%9C%93&q=is%3Aissue+
@Query("UPDATE media SET name = :name AND description = :description" +
" AND uri = :uri AND text = :text AND media_type = :mediaType" +
" WHERE id = :id")
fun update(id: Int, name: String, description: String, uri: String, text: String, mediaType: String)