[英]How to send one-off query with Relay?
I'm trying to send a one-off query using Relay. 我正在尝试使用中继发送一次性查询。 So, I don't necessarily want to use QueryRenderer
but rather have a simple API to send a query without binding the result to a React component. 因此,我不一定要使用QueryRenderer
而是要使用一个简单的API发送查询而不将结果绑定到React组件。
Previously, this was possible with the fetch
method on network
: 以前,这可以通过network
上的fetch
方法实现:
const checkVoteQueryText = `
query CheckVoteQuery($userId: ID!, $linkId: ID!) {
viewer {
allVotes(filter: {
user: { id: $userId },
link: { id: $linkId }
}) {
edges {
node {
id
}
}
}
}
}`
const checkVoteQuery = { text: checkVoteQueryText }
const result = await this.props.relay.environment._network.fetch(checkVoteQuery, {userId, linkId})
It seems however that fetch
has been deprecated in some newer version of Relay. 但是,似乎在某些较新版本的Relay中不建议使用fetch
。 Is there an alternative that can be used now? 现在有可以使用的替代方法吗?
If Relay doesn't allow for one-off queries, I'd probably just graphql-request
or plain JS fetch to get the job done. 如果Relay不允许一次性查询,我可能只是用graphql-request
或普通的JS提取来完成工作。 But it would be nice to be able to use Relay for this as it already knows my endpoint. 但是能够使用Relay会很好,因为它已经知道我的端点了。
Ah this was actually rather simple to achieve. 嗯,这实际上很容易实现。 In fact, calling fetch
on this.props.relay.environment._network
only reused the function that's passed into the Network
when it's created. 实际上,在this.props.relay.environment._network
上调用fetch
仅重用了创建时传递给Network
的函数。 So, it's possible to just reuse this function, in my case it's called fetchQuery
: 因此,可以重用此函数,在我的情况下,它称为fetchQuery
:
Environment.js
import {GC_AUTH_TOKEN} from './constants'
import { SubscriptionClient } from 'subscriptions-transport-ws'
const {
Environment,
Network,
RecordSource,
Store,
} = require('relay-runtime')
const store = new Store(new RecordSource())
// Export it here so it can be reused in other files
export const fetchQuery = (operation, variables) => {
return fetch('https://api.graph.cool/relay/v1/cj9h5g99s24fb0100nsp81d4y', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem(GC_AUTH_TOKEN)}`
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
return response.json()
})
}
const network = Network.create(fetchQuery)
const environment = new Environment({
network,
store,
})
export default environm
ent 耳鼻喉
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.