Unverified Commit 7d4821de authored by Arya Emami's avatar Arya Emami Committed by GitHub

examples: Update `with-redux` example to match the guide in Redux Toolkit docs (#59864)

parent aa914eea
......@@ -2,15 +2,15 @@
This example shows how to integrate Next.js with [Redux Toolkit](https://redux-toolkit.js.org).
The **Redux Toolkit** is a standardized way to write Redux logic (create actions and reducers, setup the store with some default middlewares like redux devtools extension). This example demonstrates each of these features with Next.js
**Redux Toolkit**(also known as "RTK" for short) provides a standardized way to write Redux logic. It includes utilities that help simplify many common use cases, including [store setup](https://redux-toolkit.js.org/api/configureStore), [creating reducers and writing immutable update logic](https://redux-toolkit.js.org/api/createreducer), and even [creating entire "slices" of state at once](https://redux-toolkit.js.org/api/createslice). This example showcases each of these features in conjunction with Next.js.
## Deploy your own
## Deploy Your Own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-redux&project-name=with-redux&repository-name=with-redux)
## How to use
## How to Use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
......
"use client";
import type { AppStore } from "@/lib/store";
import { makeStore } from "@/lib/store";
import { setupListeners } from "@reduxjs/toolkit/query";
import type { ReactNode } from "react";
import { useEffect, useRef } from "react";
import { Provider } from "react-redux";
interface Props {
readonly children: ReactNode;
}
export const StoreProvider = ({ children }: Props) => {
const storeRef = useRef<AppStore | null>(null);
if (!storeRef.current) {
// Create the store instance the first time this renders
storeRef.current = makeStore();
}
useEffect(() => {
if (storeRef.current != null) {
// configure listeners using the provided defaults
// optional, but required for `refetchOnFocus`/`refetchOnReconnect` behaviors
const unsubscribe = setupListeners(storeRef.current.dispatch);
return unsubscribe;
}
}, []);
return <Provider store={storeRef.current}>{children}</Provider>;
};
/* Core */
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export async function POST(req: Request, res: Response) {
const body = await req.json();
interface Context {
params: undefined;
}
export async function POST(request: NextRequest, context: Context) {
const body: { amount: number } = await request.json();
const { amount = 1 } = body;
// simulate IO latency
await new Promise((r) => setTimeout(r, 500));
await new Promise((resolve) => setTimeout(resolve, 500));
return NextResponse.json({ data: amount });
}
"use client";
"use client";
/* Core */
import Link from "next/link";
import { usePathname } from "next/navigation";
/* Instruments */
import styles from "../styles/layout.module.css";
export const Nav = () => {
......@@ -26,6 +25,14 @@ export const Nav = () => {
>
Verify
</Link>
<Link
className={`${styles.link} ${
pathname === "/quotes" ? styles.active : ""
}`}
href="/quotes"
>
Quotes
</Link>
</nav>
);
};
"use client";
/* Core */
import { useState } from "react";
/* Instruments */
import {
counterSlice,
useSelector,
useDispatch,
selectCount,
decrement,
increment,
incrementAsync,
incrementIfOddAsync,
} from "@/lib/redux";
import styles from "./counter.module.css";
incrementByAmount,
incrementIfOdd,
selectCount,
selectStatus,
} from "@/lib/features/counter/counterSlice";
import { useAppDispatch, useAppSelector } from "@/lib/hooks";
import styles from "./Counter.module.css";
export const Counter = () => {
const dispatch = useDispatch();
const count = useSelector(selectCount);
const [incrementAmount, setIncrementAmount] = useState(2);
const dispatch = useAppDispatch();
const count = useAppSelector(selectCount);
const status = useAppSelector(selectStatus);
const [incrementAmount, setIncrementAmount] = useState("2");
const incrementValue = Number(incrementAmount) || 0;
return (
<div>
......@@ -25,15 +29,17 @@ export const Counter = () => {
<button
className={styles.button}
aria-label="Decrement value"
onClick={() => dispatch(counterSlice.actions.decrement())}
onClick={() => dispatch(decrement())}
>
-
</button>
<span className={styles.value}>{count}</span>
<span aria-label="Count" className={styles.value}>
{count}
</span>
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(counterSlice.actions.increment())}
onClick={() => dispatch(increment())}
>
+
</button>
......@@ -43,25 +49,29 @@ export const Counter = () => {
className={styles.textbox}
aria-label="Set increment amount"
value={incrementAmount}
onChange={(e) => setIncrementAmount(Number(e.target.value ?? 0))}
type="number"
onChange={(e) => {
setIncrementAmount(e.target.value);
}}
/>
<button
className={styles.button}
onClick={() =>
dispatch(counterSlice.actions.incrementByAmount(incrementAmount))
}
onClick={() => dispatch(incrementByAmount(incrementValue))}
>
Add Amount
</button>
<button
className={styles.asyncButton}
onClick={() => dispatch(incrementAsync(incrementAmount))}
disabled={status !== "idle"}
onClick={() => dispatch(incrementAsync(incrementValue))}
>
Add Async
</button>
<button
className={styles.button}
onClick={() => dispatch(incrementIfOddAsync(incrementAmount))}
onClick={() => {
dispatch(incrementIfOdd(incrementValue));
}}
>
Add If Odd
</button>
......
.select {
font-size: 25px;
padding: 5px;
padding-top: 2px;
padding-bottom: 2px;
size: 50;
outline: none;
border: 2px solid transparent;
color: rgb(112, 76, 182);
cursor: pointer;
background-color: rgba(112, 76, 182, 0.1);
border-radius: 5px;
transition: all 0.15s;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
}
"use client";
import { useGetQuotesQuery } from "@/lib/features/quotes/quotesApiSlice";
import { useState } from "react";
import styles from "./Quotes.module.css";
const options = [5, 10, 20, 30];
export const Quotes = () => {
const [numberOfQuotes, setNumberOfQuotes] = useState(10);
// Using a query hook automatically fetches data and returns query values
const { data, isError, isLoading, isSuccess } =
useGetQuotesQuery(numberOfQuotes);
if (isError) {
return (
<div>
<h1>There was an error!!!</h1>
</div>
);
}
if (isLoading) {
return (
<div>
<h1>Loading...</h1>
</div>
);
}
if (isSuccess) {
return (
<div className={styles.container}>
<h3>Select the Quantity of Quotes to Fetch:</h3>
<select
className={styles.select}
value={numberOfQuotes}
onChange={(e) => {
setNumberOfQuotes(Number(e.target.value));
}}
>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
{data.quotes.map(({ author, quote, id }) => (
<blockquote key={id}>
&ldquo;{quote}&rdquo;
<footer>
<cite>{author}</cite>
</footer>
</blockquote>
))}
</div>
);
}
return null;
};
/* Components */
import { Providers } from "@/lib/providers";
import Image from "next/image";
import type { ReactNode } from "react";
import { StoreProvider } from "./StoreProvider";
import { Nav } from "./components/Nav";
/* Instruments */
import styles from "./styles/layout.module.css";
import "./styles/globals.css";
import styles from "./styles/layout.module.css";
interface Props {
readonly children: ReactNode;
}
export default function RootLayout(props: React.PropsWithChildren) {
export default function RootLayout({ children }: Props) {
return (
<Providers>
<StoreProvider>
<html lang="en">
<body>
<section className={styles.container}>
<Nav />
<header className={styles.header}>
<img src="/logo.svg" className={styles.logo} alt="logo" />
<Image src="/logo.svg" className={styles.logo} alt="logo" />
</header>
<main className={styles.main}>{props.children}</main>
<main className={styles.main}>{children}</main>
<footer className={styles.footer}>
<span>Learn </span>
<a
className={styles.link}
href="https://reactjs.org/"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
......@@ -33,7 +37,7 @@ export default function RootLayout(props: React.PropsWithChildren) {
<span>, </span>
<a
className={styles.link}
href="https://redux.js.org/"
href="https://redux.js.org"
target="_blank"
rel="noopener noreferrer"
>
......@@ -42,25 +46,34 @@ export default function RootLayout(props: React.PropsWithChildren) {
<span>, </span>
<a
className={styles.link}
href="https://redux-toolkit.js.org/"
href="https://redux-toolkit.js.org"
target="_blank"
rel="noopener noreferrer"
>
Redux Toolkit
</a>
,<span> and </span>
<span>, </span>
<a
className={styles.link}
href="https://react-redux.js.org/"
href="https://react-redux.js.org"
target="_blank"
rel="noopener noreferrer"
>
React Redux
</a>
,<span> and </span>
<a
className={styles.link}
href="https://reselect.js.org"
target="_blank"
rel="noopener noreferrer"
>
Reselect
</a>
</footer>
</section>
</body>
</html>
</Providers>
</StoreProvider>
);
}
/* Components */
import { Counter } from "./components/Counter/Counter";
import type { Metadata } from "next";
import { Counter } from "./components/counter/Counter";
export default function IndexPage() {
return <Counter />;
}
export const metadata = {
export const metadata: Metadata = {
title: "Redux Toolkit",
};
import { Quotes } from "../components/quotes/Quotes";
export default function QuotesPage() {
return (
<>
<h1>Quotes page</h1>
<p>This page is intended to showcase RTK Query.</p>
<Quotes />
</>
);
}
import { asyncThunkCreator, buildCreateSlice } from "@reduxjs/toolkit";
// `buildCreateSlice` allows us to create a slice with async thunks.
export const createAppSlice = buildCreateSlice({
creators: { asyncThunk: asyncThunkCreator },
});
export const fetchIdentityCount = async (
amount = 1,
): Promise<{ data: number }> => {
const response = await fetch("http://localhost:3000/api/identity-count", {
// A mock function to mimic making an async request for data
export const fetchCount = async (amount = 1) => {
const response = await fetch("http://localhost:3000/api/counter", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ amount }),
});
const result = await response.json();
const result: { data: number } = await response.json();
return result;
};
import { createAppSlice } from "@/lib/createAppSlice";
import type { AppThunk } from "@/lib/store";
import type { PayloadAction } from "@reduxjs/toolkit";
import { fetchCount } from "./counterAPI";
export interface CounterSliceState {
value: number;
status: "idle" | "loading" | "failed";
}
const initialState: CounterSliceState = {
value: 0,
status: "idle",
};
// If you are not using async thunks you can use the standalone `createSlice`.
export const counterSlice = createAppSlice({
name: "counter",
// `createSlice` will infer the state type from the `initialState` argument
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: (create) => ({
increment: create.reducer((state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1;
}),
decrement: create.reducer((state) => {
state.value -= 1;
}),
// Use the `PayloadAction` type to declare the contents of `action.payload`
incrementByAmount: create.reducer(
(state, action: PayloadAction<number>) => {
state.value += action.payload;
},
),
// The function below is called a thunk and allows us to perform async logic. It
// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
// will call the thunk with the `dispatch` function as the first argument. Async
// code can then be executed and other actions can be dispatched. Thunks are
// typically used to make async requests.
incrementAsync: create.asyncThunk(
async (amount: number) => {
const response = await fetchCount(amount);
// The value we return becomes the `fulfilled` action payload
return response.data;
},
{
pending: (state) => {
state.status = "loading";
},
fulfilled: (state, action) => {
state.status = "idle";
state.value += action.payload;
},
rejected: (state) => {
state.status = "failed";
},
},
),
}),
// You can define your selectors here. These selectors receive the slice
// state as their first argument.
selectors: {
selectCount: (counter) => counter.value,
selectStatus: (counter) => counter.status,
},
});
// Action creators are generated for each case reducer function.
export const { decrement, increment, incrementByAmount, incrementAsync } =
counterSlice.actions;
// Selectors returned by `slice.selectors` take the root state as their first argument.
export const { selectCount, selectStatus } = counterSlice.selectors;
// We can also write thunks by hand, which may contain both sync and async logic.
// Here's an example of conditionally dispatching actions based on current state.
export const incrementIfOdd =
(amount: number): AppThunk =>
(dispatch, getState) => {
const currentValue = selectCount(getState());
if (currentValue % 2 === 1 || currentValue % 2 === -1) {
dispatch(incrementByAmount(amount));
}
};
// Need to use the React-specific entry point to import `createApi`
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
interface Quote {
id: number;
quote: string;
author: string;
}
interface QuotesApiResponse {
quotes: Quote[];
total: number;
skip: number;
limit: number;
}
// Define a service using a base URL and expected endpoints
export const quotesApiSlice = createApi({
baseQuery: fetchBaseQuery({ baseUrl: "https://dummyjson.com/quotes" }),
reducerPath: "quotesApi",
// Tag types are used for caching and invalidation.
tagTypes: ["Quotes"],
endpoints: (build) => ({
// Supply generics for the return type (in this case `QuotesApiResponse`)
// and the expected query argument. If there is no argument, use `void`
// for the argument type instead.
getQuotes: build.query<QuotesApiResponse, number>({
query: (limit = 10) => `?limit=${limit}`,
// `providesTags` determines which 'tag' is attached to the
// cached data returned by the query.
providesTags: (result, error, id) => [{ type: "Quotes", id }],
}),
}),
});
// Hooks are auto-generated by RTK-Query
// Same as `quotesApiSlice.endpoints.getQuotes.useQuery`
export const { useGetQuotesQuery } = quotesApiSlice;
// This file serves as a central hub for re-exporting pre-typed Redux hooks.
import { useDispatch, useSelector, useStore } from "react-redux";
import type { AppDispatch, AppStore, RootState } from "./store";
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();
export const useAppStore = useStore.withTypes<AppStore>();
"use client";
/* Core */
import { Provider } from "react-redux";
/* Instruments */
import { reduxStore } from "@/lib/redux";
export const Providers = (props: React.PropsWithChildren) => {
return <Provider store={reduxStore}>{props.children}</Provider>;
};
/* Core */
import { createAsyncThunk } from "@reduxjs/toolkit";
/* Instruments */
import type { ReduxState, ReduxDispatch } from "./store";
/**
* ? A utility function to create a typed Async Thunk Actions.
*/
export const createAppAsyncThunk = createAsyncThunk.withTypes<{
state: ReduxState;
dispatch: ReduxDispatch;
rejectValue: string;
}>();
export * from "./store";
export * from "./slices";
/* Core */
import { createLogger } from "redux-logger";
const middleware = [
createLogger({
duration: true,
timestamp: false,
collapsed: true,
colors: {
title: () => "#139BFE",
prevState: () => "#1C5FAF",
action: () => "#149945",
nextState: () => "#A47104",
error: () => "#ff0005",
},
predicate: () => typeof window !== "undefined",
}),
];
export { middleware };
/* Instruments */
import { counterSlice } from "./slices";
export const reducer = {
counter: counterSlice.reducer,
};
/* Core */
import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
/* Instruments */
import { incrementAsync } from "./thunks";
const initialState: CounterSliceState = {
value: 0,
status: "idle",
};
export const counterSlice = createSlice({
name: "counter",
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload;
},
},
// The `extraReducers` field lets the slice handle actions defined elsewhere,
// including actions generated by createAsyncThunk or in other slices.
extraReducers: (builder) => {
builder
.addCase(incrementAsync.pending, (state) => {
state.status = "loading";
})
.addCase(incrementAsync.fulfilled, (state, action) => {
state.status = "idle";
state.value += action.payload;
});
},
});
/* Types */
export interface CounterSliceState {
value: number;
status: "idle" | "loading" | "failed";
}
export * from "./counterSlice";
export * from "./thunks";
export * from "./selectors";
/* Instruments */
import type { ReduxState } from "@/lib/redux";
// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`
export const selectCount = (state: ReduxState) => state.counter.value;
/* Instruments */
import { createAppAsyncThunk } from "@/lib/redux/createAppAsyncThunk";
import { fetchIdentityCount } from "./fetchIdentityCount";
import { selectCount } from "./selectors";
import { counterSlice } from "./counterSlice";
import type { ReduxThunkAction } from "@/lib/redux";
// The function below is called a thunk and allows us to perform async logic. It
// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
// will call the thunk with the `dispatch` function as the first argument. Async
// code can then be executed and other actions can be dispatched. Thunks are
// typically used to make async requests.
export const incrementAsync = createAppAsyncThunk(
"counter/fetchIdentityCount",
async (amount: number) => {
const response = await fetchIdentityCount(amount);
// The value we return becomes the `fulfilled` action payload
return response.data;
},
);
// We can also write thunks by hand, which may contain both sync and async logic.
// Here's an example of conditionally dispatching actions based on current state.
export const incrementIfOddAsync =
(amount: number): ReduxThunkAction =>
(dispatch, getState) => {
const currentValue = selectCount(getState());
if (currentValue % 2 === 1) {
dispatch(counterSlice.actions.incrementByAmount(amount));
}
};
/* Core */
import {
configureStore,
type ThunkAction,
type Action,
} from "@reduxjs/toolkit";
import {
useSelector as useReduxSelector,
useDispatch as useReduxDispatch,
type TypedUseSelectorHook,
} from "react-redux";
/* Instruments */
import { reducer } from "./rootReducer";
import { middleware } from "./middleware";
export const reduxStore = configureStore({
reducer,
middleware: (getDefaultMiddleware) => {
return getDefaultMiddleware().concat(middleware);
},
});
export const useDispatch = () => useReduxDispatch<ReduxDispatch>();
export const useSelector: TypedUseSelectorHook<ReduxState> = useReduxSelector;
/* Types */
export type ReduxStore = typeof reduxStore;
export type ReduxState = ReturnType<typeof reduxStore.getState>;
export type ReduxDispatch = typeof reduxStore.dispatch;
export type ReduxThunkAction<ReturnType = void> = ThunkAction<
ReturnType,
ReduxState,
unknown,
Action
>;
import type { Action, ThunkAction } from "@reduxjs/toolkit";
import { combineSlices, configureStore } from "@reduxjs/toolkit";
import { counterSlice } from "./features/counter/counterSlice";
import { quotesApiSlice } from "./features/quotes/quotesApiSlice";
// `combineSlices` automatically combines the reducers using
// their `reducerPath`s, therefore we no longer need to call `combineReducers`.
const rootReducer = combineSlices(counterSlice, quotesApiSlice);
// Infer the `RootState` type from the root reducer
export type RootState = ReturnType<typeof rootReducer>;
// `makeStore` encapsulates the store configuration to allow
// creating unique store instances, which is particularly important for
// server-side rendering (SSR) scenarios. In SSR, separate store instances
// are needed for each request to prevent cross-request state pollution.
export const makeStore = () => {
return configureStore({
reducer: rootReducer,
// Adding the api middleware enables caching, invalidation, polling,
// and other useful features of `rtk-query`.
middleware: (getDefaultMiddleware) => {
return getDefaultMiddleware().concat(quotesApiSlice.middleware);
},
});
};
// Infer the return type of `makeStore`
export type AppStore = ReturnType<typeof makeStore>;
// Infer the `AppDispatch` type from the store itself
export type AppDispatch = AppStore["dispatch"];
export type AppThunk<ThunkReturnType = void> = ThunkAction<
ThunkReturnType,
RootState,
unknown,
Action
>;
......@@ -6,18 +6,16 @@
"start": "next start"
},
"dependencies": {
"@reduxjs/toolkit": "1.9.5",
"@reduxjs/toolkit": "^2.2.0",
"next": "latest",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-redux": "8.1.0"
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0"
},
"devDependencies": {
"@types/node": "20.3.1",
"@types/react": "18.2.8",
"@types/react-dom": "18.2.5",
"@types/redux-logger": "3.0.9",
"redux-logger": "3.0.6",
"typescript": "5.1.3"
"@types/node": "20.2.5",
"@types/react": "18.2.37",
"@types/react-dom": "^18.2.18",
"typescript": "^5.3.3"
}
}
......@@ -11,7 +11,7 @@
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "ESNEXT",
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment