Wondering how to leverage TypeScript, Next-redux-wrapper, and getServerSideProps in your project?

Transitioning from JavaScript to TypeScript for my codebase is proving to be quite challenging.

// store.ts

import { applyMiddleware, createStore, compose, Store } from "redux";
import createSagaMiddleware, { Task } from "redux-saga";
import { createWrapper } from "next-redux-wrapper";
import { composeWithDevTools } from "redux-devtools-extension";

import reducer from "./reducers";
import rootSaga from "./sagas";

const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  const middlewares = [sagaMiddleware];
  const enhancer =
    process.env.NODE_ENV === "production"
      ? compose(applyMiddleware(...middlewares))
      : composeWithDevTools(applyMiddleware(...middlewares));
  const store = createStore(reducer, enhancer);
  store.sagaTask = sagaMiddleware.run(rootSaga);
  return store;
};

const wrapper = createWrapper(configureStore, {
  debug: process.env.NODE_ENV === "development",
});

export default wrapper;
// reducers/index.ts

import { HYDRATE } from "next-redux-wrapper";
import { AnyAction, combineReducers } from "redux";

import url, { IUrlReducerState } from "./reducer_url";
import user, { IUserReducerState } from "./reducer_user";

export type State = {
  url: IUrlReducerState;
  user: IUserReducerState;
};

const rootReducer = (state: State, action: AnyAction) => {
  switch (action.type) {
    case HYDRATE:
      return action.payload;

    default: {
      const combineReducer = combineReducers({
        url,
        user,
      });
      return combineReducer(state, action);
    }
  }
};
export type RootState = ReturnType<typeof rootReducer>;
export default rootReducer;

reducers/index.ts - Is this the correct way to implement it? I made some modifications.

// pages/index.tsx

import { END } from "redux-saga";
import wrapper from "../store";

export const getServerSideProps = wrapper.getServerSideProps(
  async (context) => {

    context.store.dispatch({
      type: LOAD_USER_REQUEST,
    });

    context.store.dispatch(END);
    await context.store.sagaTask.toPromise();
  }
);

I've been referring to the official documentation, but I'm still struggling with understanding: https://github.com/kirill-konshin/next-redux-wrapper#getserversideprops

While these codes worked perfectly in JavaScript, transitioning to TypeScript has presented some challenges.

Answer №1

These are the issues that need attention:

  1. An error will occur in createStore(reducer, enhancer) because the reducer does not align with the required type
    (state: State | undefined, action: AnyAction) => State
    . The current reducer does not permit the state to be undefined.

Adjustment:

const rootReducer = (state: State | undefined, action: AnyAction): State => {
  1. An error will emerge at
    store.sagaTask = sagaMiddleware.run(rootSaga);
    due to the absence of a property called sagaTask within the redux-generated store object. Further details on this issue can be found here.

Solution inspired by next-redux-wrapper documentation:

Create a new interface for your store incorporating the task:

export interface SagaStore extends Store<State, AnyAction> {
  sagaTask: Task;
}

Replace:

(store as SagaStore).sagaTask = sagaMiddleware.run(rootSaga);

With:

await (context.store as SagaStore).sagaTask.toPromise();

Answer №2

When I was working on syncing Redux with Next.js, I faced some challenges. Eventually, I managed to create a project template that successfully integrates Redux with Next.js using next-redux-wrapper. You can check out the project template here:

https://github.com/felipemeriga/next-typescript-redux-template

The wrapper setup looks like this:

const thunkMiddleware = thunk.withExtraArgument({}) as ThunkMiddleware<IStoreState, AnyAction>;

// Create makeStore function
const makeStore: MakeStore<IStoreState> = (context: Context) => createStore(reducers, composeWithDevTools(applyMiddleware(thunkMiddleware)));

export type ExtraArgument = {};

export type ThunkCreator<R = Promise<any>> = ActionCreator<ThunkAction<R, IStoreState, ExtraArgument, AnyAction>>;

const wrapper = createWrapper<IStoreState>(makeStore, {debug: false});

export default wrapper;

I also made changes to the _app.tsx file:

// If you want to use the redux wrapper for pages, override _app.tsx with this code snippet
class MyApp extends App {
    static async getInitialProps({Component, ctx}) {
        return {
            pageProps: {
                ...(Component.getInitialProps ? await Component.getInitialProps(ctx) : {}),
            }
        };
    }

    render() {
        const {Component, pageProps} = this.props;
        return (
            <Component {...pageProps} />
        );
    }

}

export default wrapper.withRedux(MyApp);

Lastly, I integrated the wrapper into the index.tsx component:

interface IProps {
    tick: ITickState
    updateAnnouncement: any
}

interface IState {}

interface IDispatchProps {
    onUpdateTick: (message: string) => ITickState,
    thunkAsyncFunction: () => Promise<any>;
}

type Props = IProps & IState & IDispatchProps

class App extends React.Component<Props> {

    constructor(props: Props) {
        super(props);
    }

    async componentWillUnmount(): Promise<void> {
        await this.props.thunkAsyncFunction();
    }

    render() {
        return (
            <Layout title="Home | Next.js + TypeScript Example">
                <h1>Hello Next.js 👋</h1>
                <p>
                    <Link href="/about">
                        <a>About</a>
                    </Link>
                </p>
                <div>
                    The current tick state: {this.props.tick.message}
                </div>
            </Layout>
        );
    }
}

const mapStateToProps = (state: IStoreState): {tick: ITickState} => ({
    tick: getTickState(state)
});

const mapDispatchToProps = (dispatch: any): IDispatchProps => {
    return {
        onUpdateTick: (message: string) =>
            dispatch(updateTick(message)),
        thunkAsyncFunction: () => dispatch(thunkAsyncFunction())
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

export const getStaticProps = wrapper.getStaticProps(
    ({}) => {
    }
);

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

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

Achieving seamless integration among react-templates, TypeScript, and webpack

I am attempting to integrate TypeScript, react-templates, and webpack for a seamless workflow. My starting point was the sample code provided at https://www.typescriptlang.org/docs/handbook/react-&-webpack.html. The configuration in the webpack.config ...

Having trouble writing Jest test cases for a function that returns an Observable Axios response in Nest JS

I'm relatively new to the NestJS + Typescript + RxJs tech stack and I'm attempting to write a unit test case using Jest for one of my functions. However, I'm uncertain if I'm doing it correctly. component.service.ts public fetchCompon ...

How to apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...

Error encountered in NextJS API: "TypeError: res.status is not a function"

Background In my development environment, I am using NextJS v11.1.1-canary.11, React v17.0.2, and Typescript v4.3.5. To set up a basic API endpoint following the guidelines from NextJS Typescript documentation, I created a file named login.tsx in the pag ...

Encountering a "Command Not Found" error after a successful installation of AWS Amplify CLI using NPM or CURL

Trying to link my amplify backend with my Next JS application is proving to be challenging. I have installed Amplify CLI globally using both NPM and CURL on Mac OS, but despite successful installations, the "amplify" command is not recognized. Commands At ...

Edit the CSS styles within a webview

When loading the page in NativeScript using web viewing, I encountered a need to hide certain elements on the page. What is the best way to apply CSS styles to HTML elements in this scenario? Are there any alternatives that could be considered? I have been ...

Using TypeScript to test a Vue3 component that includes a slot with Cypress

I'm currently facing challenges setting up a new project. The technologies I am using include Vue3, TypeScript, and Cypress. It seems like the problem lies within the TypeScript configuration. Below is a Minimal Working Example (MWE) of my setup. Any ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Experimenting with a module reliant on two distinct services

I am facing an issue with a component that relies on a service to fetch data. The service also retrieves configurations from a static variable in the Configuration Service, but during Karma tests, the const variable is showing up as undefined. Although I ...

Obtaining the date input value from the ng2-date-picker component in Angular2

I am struggling to extract the value from a date picker input field (ng2-date-picker). Despite attempting various methods to retrieve the value, I have not been successful. For reference, here is the link to the npm package I am utilizing. This represent ...

Having trouble personalizing the theme on Next.js with Shadcn integration

I attempted to modify the theme by copying and pasting styles from into global.css, but unfortunately, it didn't produce the desired effect. Here is the default and current global.css code: @tailwind base; @tailwind components; @tailwind utilities; ...

What factors contribute to 'tslib' having more downloads than 'typecrypt'?

How is it possible that 'tslib', a library for 'typescript', has more downloads than 'typescript' itself? If one does not use 'typescript', then they cannot utilize 'tslib' as well. Just because someone us ...

Encountering an issue: The API call for /api/orders was resolved but no response was sent, potentially causing requests to become stuck in Next.js

Struggling with an error while working on an ecommerce website using Next.js. The error message reads: error: API resolved without sending a response for /api/orders, this may result in stalled requests The error also indicates: API handler should not ...

What is the best way to specify a function type that takes an argument of type T and returns void?

I am in search of a way to create a type that can accept any (x: T) => void function: let a: MyType; a = (x: number) => {}; // (x: number) => void a = (x: string) => {}; // (x: string) => void a = (x: SomeInterface) => {}; / ...

Tips for invoking a function on a react-bootstrap-table component using TypeScript

One issue I'm encountering is trying to cast the "any" bootstrapTableRef to react-bootstrap-table, setting up the ref correctly, or importing it incorrectly. I am struggling to access the method of the imported table. While I found a solution using th ...

Encountering an Error When Trying to Run Npm Install in React-Native

I encountered an issue while trying to perform an npm install on my project, so I deleted the node modules folder in order to reinstall it. However, even after running npm install in the appropriate directory, I continued to face numerous errors in my term ...

Is the Property Decorator failing to substitute the definition?

My code is similar to the following scenario, where I am attempting to replace a property based on a decorator export function DecorateMe() { return function(component: any, propertyKey: string) { Object.defineProperty(component, propertyKey, ...

Can one inherit under specific conditions?

I have just started exploring the OOP paradigm and I am curious to know if it is possible to have conditional inheritance in TypeScript. This would help avoid repeating code. Here is what I have in mind. Any suggestions or recommendations are greatly appre ...

Sending an event from a child component to another using parent component in Angular

My form consists of two parts: a fixed part with the Save Button and a modular part on top without a submit button. I have my own save button for performing multiple tasks before submitting the form, including emitting an Event to inform another component ...