I'm working with two API endpoints. The first one returns a list of dates in a string format for which data is available. The date can then be added to the second endpoint and renders additional data. On the Graphql Playground I have been able to make it all work. On the front-end I have a select option drop down for the dates, but I have not been able to fire off the second API call when I click on any given date. It's the first time I'm using graphql mutation and I haven't been able to get the second API request to return any data when I select a date. Thank you.
Front-end code:
app.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
query.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
}
}
`
Back-end code:
server.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]
resolver.js
module.exports = {
Query: {
mapDates: (_, __, { dataSources }) => dataSources.irriSatAPI.getMapsDates(),
},
Mutation: {
mapDate: (_, { date }, { dataSources }) => dataSources.irriSatAPI.getMapsLayer(date)
}
}