Improving the method of retrieving RTK result within getServerSideProps

Currently, I am utilizing RTK Query to make an API call within my getServerSideProps function. While I can successfully retrieve the result using the code snippet provided below, I find the process somewhat awkward. Additionally, the result lacks proper typing, which is suboptimal.

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: {},
    }
  },
)

I'm seeking a more efficient approach for handling this situation. Any suggestions?

Answer №1

Do you really want to execute a mutation on the server-side rendering? Mutations are typically used to modify data in the database, and this should generally happen based on user interactions rather than during page rendering. In such cases, it's better to use queries!

If you still need to access the API state, here are two ways to do it:

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

// For mutations, you'll need the requestId
const runningMutation = dispatch(api.endpoints.apiCall.initiate(arguments))
const mutationResult = api.endpoints.apiCall.select({ requestId: runningMutation.requestId })(getState())

In most cases, passing data as props into your component is not necessary - instead, the component can simply call useApiCallQuery(arguments) to retrieve the results from the server-query as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The module '@sanity/vision' or its type declarations could not be located

./sanity/sanity.config.ts:3:26 Type error: Unable to locate module '@sanity/vision' or its corresponding type declarations. 1 | import {defineConfig} from 'sanity' 2 | import {deskTool} from 'sanity/desk' 3 | import {visionT ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

Upon calling set() on Map, the object returned does not conform to a Map data structure

I've been exploring the transition to using immutable.js for managing states: class Register extends Component<{}, Map<string, string>> { state = Map<string, string>(); onInputValueChange(e) { const { name, value } ...

Fixing the "Package Manager Not Found" Issue when Deploying a Next.js Project on Vercel

Having created a website using Next.js and aiming to deploy it on Vercel, I encountered an error during the deployment process despite meticulously following the configuration steps. The error message displayed was: "Unable to determine package manage ...

What are the properties used in functional components of React?

Seeking guidance on passing React component props to another component: interface IMyComponent { props: Props<any> } const MyComponent: FC = ({ props }) => { } Previously, I attempted to utilize the React.Props type after consulting this que ...

Set the array as the object attribute

Transitioning my app from AngularJs to Angular 4 has been quite a challenge. I've noticed that the type of statements I frequently used in my code are now failing in Angular 4 (TypeScript): Update: The following lines were previously used in Angular ...

Ionic - What is the correct way to import ViewController? - Uncaught (in promise): Error: ViewController provider not found

I have a Popover in my app and I want it to behave differently based on the selected item. I followed the instructions in the Ionic documentation to achieve this. Error: Uncaught (in promise): Error: No provider for ViewController! When I tried adding ...

What is the best way to ensure that multiple queries are returned in the correct sequence?

In the interface below, there is a search input box along with data displayed. As you type in the search input, the data below filters accordingly. Each letter typed triggers a request to retrieve the relevant data. For instance, if you type "folder," the ...

Saving secure tokens in NextJS

Looking to connect an App developed with Next.js and Salesforce Marketing Cloud through OAuth integration. Once the user logs in, they are redirected back to the Next.js App with an authorization code, which is used to request access and refresh tokens. h ...

Real-time monitoring within a callback function in Angular 5

I need to ensure that a specific callback is executed only after receiving a response, starting from the line this.groupDefaultExpanded = -1; onwards. loadLoginDetails() { this.derivativeSpecService.getDerivativeDetails().subscribe( res => ...

Managing compatibility with IE11 for all dependent packages: Best practices

Currently, I am working on a React app using version 17.0 and Next.js version 11.1.2 among other stacks. While Next.js typically supports IE11 by default, I have encountered issues with compatibility after adding certain packages to my project. The consol ...

Can we securely retrieve nested properties from an object using an array of keys in TypeScript? Is there a method to accomplish this in a manner that is type-safe and easily combinable?

I wish to create a function that retrieves a value from an object using an array of property keys. Here's an example implementation: function getValue<O, K extends ObjKeys<O>>(obj: O, keys: K): ObjVal<O,K> { let out = obj; for (c ...

I thought removing the redirect from Next.config.js would stop it from redirecting, but it seems to still be redirecting

Could anyone help me understand why my next.config.js file is not being updated when changes are made, even after I rerun it? Any advice on how to make sure it updates correctly would be greatly appreciated. ...

Exploring the creation of Request Headers

In my NextJS application, I have noticed that JavaScript resources are not being gzipped when accessed on mobile devices (while they work fine on desktop). After investigating further, I discovered that this is due to the lack of an Accept-Encoding header ...

What are the appropriate scenarios for extending and utilizing an abstract class in Angular?

@Component({ selector: 'my-component', template: `<ng-content></ng-content>`, providers: [ { provide: AbstractClass, useExisting: forwardRef(() => TargetComponent) } ] }) export class TargetComponent extends AbstractCla ...

Strange Typescript Issue: Dependency Imports Not Recognized as Top-Level Module

Attempting to move a custom token from one account to another by following this detailed tutorial. Facing an issue with four errors showing up for all imports from the @solana/spl-token package. Tried removing the node-modules folder and reinstalling npm ...

Unable to utilize React hooks in Next.js header

Welcome to my website . I am looking to reduce the padding on the header when the user scrolls. To achieve this, I have created the following component: import Link from 'next/link' import Image from 'next/image' import { GET_HEADER ...

My website is experiencing issues with LCP specifically on mobile devices. Instead of receiving a score, I am only presented with a question mark

After developing a website for a client, I noticed that while the desktop score was good, the mobile measurements resulted in an error. This issue could potentially impact the site's performance on Google. I suspect the animations rendered with lottie ...

What is the process for transferring a Pulumi Output<T> to the container definition of a task in ECS?

When creating a generic ECS service that deals with dynamic data, it is important to note that the containerDefinition within a Task Definition must be provided as a single valid JSON document. The code snippet for this setup looks like: genericClientServi ...

I have a question about TypeScript mapped types. Why is it not possible to retrieve the keys of a union of interfaces?

Below is the code snippet that I am working with: interface Data { A: { a1: string; a2: string; }; B: { b1: number; b2: string; }; } type TransformDataKey<V extends string, T extends string> = `--${V}-${T}`; type TransformDa ...