Andreas Köberle
Andreas Köberle

Reputation: 110922

How to enhance the response in apollo client with react only once

I make a GraphQL query where I get back a lot of data and than I calculate the min and max values. As the calculating is quite time consuming I would like to only do it when I receive the value. Unfortunately the props method is called every time the component is rerendered even there was no new call, and the data comes from the store. How can I limit the calculation to the points where I really get new data

graphql(DataQuery, {
    options: ({ id }) => ({
        variables: {
            id,
        },
    }),
    props: ({ data: { result} }) => ({
        data: result,
        min: getMin(result),
        max: getMax(result),
    }),
})

Upvotes: 2

Views: 132

Answers (1)

trixn
trixn

Reputation: 16309

This problem is similar to the problem in redux where mapStateToProps() will be called again every time the store updates repeating costy calculations.

You can solve that by using memorized selectors:

import { createSelector } from 'reselect'

const getMinMax = createSelector(
  result => result,
  result => ({
      min: getMin(result),
      max: getMax(result),
  })
)

graphql(DataQuery, {
    options: ({ id }) => ({
        variables: {
            id,
        },
    }),
    props: ({ data: {result} }) => ({
        data: result,
        ...getMinMax(result), // will only re-calculate if result changed
    }),
})

Memorized selectors remember the last result of a call and keep returning that on subsequent calls as long as the input does not change.

Upvotes: 3

Related Questions