我正在使用两个 API 端点。第一个以字符串格式返回日期列表,其中数据可用。然后可以将日期添加到第二个端点并呈现其他数据。在 Graphql Playground 上,我已经能够完成所有工作。在前端,我有一个日期选择选项下拉菜单,但是当我单击任何给定日期时,我无法触发第二个 API 调用。这是我第一次使用 graphql 突变,当我选择日期时,我无法获得第二个 API 请求以返回任何数据。谢谢你。
前端代码:
应用程序.tsx
import * as React from 'react'
import { useState } from 'react'
import { useMutation } from '@apollo/react-hooks'
import { IrriSatQuery } from '../../generated/graphql'
import { MAP_LAYER } from './query'
interface Props {
data: IrriSatQuery;
}
const IrriSat: React.FC<Props> = ({ data }) => {
const [option, setOption] = useState((data?.mapDates as any)[0].date!)
const [getLayer] = useMutation(MAP_LAYER)
return (
<>
<ContentWrapper>
<select value={option} onChange={( e: React.ChangeEvent<HTMLSelectElement>, ): void => {setOption(e.target.value, getLayer(e.target.value)}} onSelect={() => getLayer({variables: {type: option}})}>
{data?.mapDates?.slice(0,52).map(res =>
<option key={res?.date!} value={res?.date!}>{res?.date}</option>
)
}
</select>
</ContentWrapper>
</>
)
}
export default IrriSat
查询.ts
export const QUERY_IRR_SAT = gql`
query IrriSat {
mapDates {
date
dateurl
}
}
`
export const MAP_LAYER = gql`
mutation MapLayer($date: String!) {
mapDate(date: $date) {
token
mapid
name
}
}
`
后端代码:
服务器.js
class IrriSatAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://irrisat-cloud.appspot.com/_ah/api/irrisat/v1/services/'
}
async getMapsDates() {
const response = await this.get('maps/dates')
return Array.isArray(response.items) ? response.items.map(response => this.mapsDatesReducer(response)) : []
}
mapsDatesReducer(response) {
return {
date: response.date,
dateurl: response.dateurl,
}
}
async getMapsLayer(date) {
const response = await this.get(`maps/layers/${date}`)
return Array.isArray(response.items) ? response.items.map(response => this.mapsLayerReducer(response)) : []
}
mapsLayerReducer(response) {
return {
token: response.token,
mapid: response.mapid,
name: response.name
}
}
}
}
schema.js
type MapDates {
date: String
dateurl: String
}
type Mutation {
mapDate(date: String): [MapsLayers]
}
type Query {
mapDates: [MapDates]
解析器.js
module.exports = {
Query: {
mapDates: (_, __, { dataSources }) => dataSources.irriSatAPI.getMapsDates(),
},
Mutation: {
mapDate: (_, { date }, { dataSources }) => dataSources.irriSatAPI.getMapsLayer(date)
}
}