问题
I just started using react-apollo and was wondering what was the best way to share data across components.
For example, I have componentA
which is using grapql
from react-apollo
to fetch some data (WrappedA
). I also have some other component, componentB
, somewhere else in my UI and want to use the data already fetched by componentA
.
Attached a very simple example below.
const ComponentA = ({ ...props }) => (
<div>
ComponentA...
id: {props.organisationsData.organisations.id}
</div>
)
const ComponentB = ({ ...props }) => (
<div>
****** Want to access props.organisationsData *****
ComponentB...
</div>
)
const organisationsQuery = gql`
query organisations {
organisations {
id
name
}
}
`
const WrappedA = graphql(organisationsQuery, { name: 'organisationsData' })(WrappedA)
const Container = ({ ...props }) => (
<div>
<WrappedA />
<ComponentB />
</div>
)
According to the apollo documentation (https://www.apollographql.com/docs/react/basics/setup.html#in-your-ui) ideally the query is tied to the UI component.
I can wrap componentB
with the same organisationsQuery
and it will use the cache but I wont be able to co-locate my query to my main UI part. I could not find any info related to sharing data across components.
When I tried
const WrappedB = graphql(gql`
query organisations {
organisations {
id
}
}
`, { name: 'organisationsData' })(WrappedB)
(leaving out name
) I saw an extra call made to the graphql endpoint.
This is not ideal.
What would be the best way to access data already fetched from the server? (using v2 so cannot use an existing redux store, accessing the cache manually seems low level and this use case is not mentioned on the site: https://www.apollographql.com/docs/react/basics/caching.html)
Thank you.
回答1:
you can use apollo link , this is local state management , you can read documentation
apollo-link-state allows you to store your local data inside the Apollo cache alongside your remote data. To access your local data, just query it with GraphQL. You can even request local and server data within the same query!
https://www.apollographql.com/docs/react/essentials/local-state.html
来源:https://stackoverflow.com/questions/48349355/apollo-graphql-react-data-sharing-across-components