Better way of getting RTK result in getServerSideProps

Viewed 104

I'm using RTK Query to call an API in my getServerSideProps function. I can get the result within the function using the code below, but it feels kind of awkward. Also, the result is not typed, which would be preferable.

export const getServerSideProps: GetServerSideProps = wrapper.getServerSideProps(
  (store) => async (context: GetServerSidePropsContext) => {
    await store.dispatch(apiCall.initiate({ ...someParams }))
    await Promise.all(api.util.getRunningOperationPromises())

    const mutations = store.getState().api.mutations;
    const mutation = Object.values(mutations).find((m) => m?.endpointName === 'apiCall')
    //   |________| -> type is `unknown`
    
    if (mutation?.error) {
      const error = mutation.error as {
        status: number
        data: {
          error: string
        }
      }
    }

    return {
      props: {},
    }
  },
)

Is there a better way of doing this?

1 Answers

Are you sure that you want to call a mutation on SSR? A mutation is meant to change something on the database - that should usually occur on user interaction, not on page render. For that you should always use a query!

Apart from that, you can do one of these two to get that api state:

// for a query:
const queryResult = api.endpoints.apiCall.select(arguments)(getState())

// for a mutation you need to know the requestId
const runningMutation = dispatch(api.endpoints.apiCall.initiate(arguments))
const mutationResult = api.endpoints.apiCall.select({ requestId: runningMutation.requestId })(getState())

That said, you probably won't have a lot of reason to do this - there is no good reason to pass that data as props into your component - the component can just call useApiCallQuery(arguments) and get the results for the query that was done on the server - that's how it's meant to be used.

Related