首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据react-apollo中的查询结果更新本地配置

根据react-apollo中的查询结果更新本地配置
EN

Stack Overflow用户
提问于 2018-11-23 21:06:15
回答 1查看 364关注 0票数 0

使用apollo和react,我想根据(远程) apollo查询的结果更新我的本地apollo状态。

查询的类型为[String!]!,我的本地州包含类型为String的{ name }。我希望将本地{ name }分配给查询返回的第一个项目。

代码语言:javascript
复制
const App = compose(
    graphql(gql`{ name @client }`, { name: 'localData' }),
    graphql(gql`{ currencies { name } }`)
)(({ localData }) => <h1>{ localData.name }</h1>)

我不想使用componentWillReceiveProps (一旦来自远程查询的道具就在那里改变本地状态),因为这是不好的做法。

我需要使用本地apollo状态,而不仅仅是组件的状态,因为这个值将被其他组件使用。

我尝试使用graphql组的props配置,但感觉和componentWillReceiveProps一样糟糕,并导致无限循环。

有什么想法吗?

相关版本控制:

代码语言:javascript
复制
"apollo-boost": "^0.1.19",
"apollo-link-state": "^0.4.2",
"react-apollo": "^2.2.4",

代码

代码语言:javascript
复制
import React from 'react'
import ReactDOM from 'react-dom'
import ApolloClient from 'apollo-boost'
import gql from 'graphql-tag'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloProvider, graphql, compose } from 'react-apollo'
import { ApolloLink } from 'apollo-link'
import { withClientState } from 'apollo-link-state'
import { HttpLink } from 'apollo-link-http'

const resolvers = {
    Mutation: {
        updateName: (ops, { name }, { cache }) => cache.writeData({ data: { name } })
    }
}
const typedefs = gql`
  type Query {
    name: String
  }
  type Mutation {
    updateName(name: String): String
  }
`
const defaults = { name: 'defaultName' }
const cache = new InMemoryCache()
const stateLink = withClientState({
    cache,
    defaults,
    resolvers
});
const apolloClient = new ApolloClient({
    uri: '/store/api/graphql',
    link: ApolloLink.from([stateLink, new HttpLink()]),
    cache,
    clientState: {
        defaults,
        resolvers,
        typedefs
    }
})

const App = compose(
    graphql(gql`{ name @client }`, { name: 'localData' }),
    graphql(gql`{ currencies { name id } }`)
)(({ localData }) => <h1>{ localData.name }</h1>)

ReactDOM.render(
    <ApolloProvider client={ apolloClient }>
        <App />
    </ApolloProvider>,
    document.getElementById('app')
)
EN

回答 1

Stack Overflow用户

发布于 2018-11-23 21:34:14

我找到了一个使用Query组件而不是graphql hoc的解决方案。查询组件具有onCompleted属性,我可以在其中传递一个更新本地状态的函数:

代码语言:javascript
复制
const UPDATE_NAME = gql`mutation ($name: String) {
    updateName (name: $name) @client { name }
}`
const App = compose(
    withApollo,
    graphql(gql`{ name @client }`, { name: 'localData' })
)(({ client, localData }) => <Query
    query={ gql`{ currencies { name id } }` }
    onCompleted={ data =>
        client.mutate({
            mutation: UPDATE_NAME,
            variables: { name: data.currencies[0].name }
        })
    }>
    {
        () => <h1>Current: { localData.name }</h1>
    }
</Query>)

我发现Query组件不如graphql hoc优雅,但至少是一个解决方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53447280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档