Upgrade with-redux example to app router (#49994)
### What? Update **with-redux** example. ### Why? **with-redux** example have: - outdated packages - outdated approaches and relies on **pages** directory Since **app router** is stable now and is recommended to use, I've updated this example. ### How? An update includes: - move example to **app router** - update **package.json** deps to the latest versions - modernize jest by switching from **ts-node** to **@swc/jest** - fix and overhaul **tests** - modernize **redux** infra - overhaul example **source code quality** Co-authored-by: Balázs Orbán <18369201+balazsorban44@users.noreply.github.com>
This commit is contained in:
parent
cbb69b2cfc
commit
04cd1fd4ef
38 changed files with 478 additions and 489 deletions
12
examples/with-redux/app/api/identity-count/route.ts
Normal file
12
examples/with-redux/app/api/identity-count/route.ts
Normal file
|
@ -0,0 +1,12 @@
|
|||
/* Core */
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
export async function POST(req: Request, res: Response) {
|
||||
const body = await req.json()
|
||||
const { amount = 1 } = body
|
||||
|
||||
// simulate IO latency
|
||||
await new Promise((r) => setTimeout(r, 500))
|
||||
|
||||
return NextResponse.json({ data: amount })
|
||||
}
|
|
@ -1,22 +1,23 @@
|
|||
'use client'
|
||||
|
||||
/* Core */
|
||||
import { useState } from 'react'
|
||||
|
||||
import { useAppSelector, useAppDispatch } from '../../hooks'
|
||||
/* Instruments */
|
||||
import {
|
||||
decrement,
|
||||
increment,
|
||||
incrementByAmount,
|
||||
incrementAsync,
|
||||
incrementIfOdd,
|
||||
counterSlice,
|
||||
useSelector,
|
||||
useDispatch,
|
||||
selectCount,
|
||||
} from './counterSlice'
|
||||
import styles from './Counter.module.css'
|
||||
incrementAsync,
|
||||
incrementIfOddAsync,
|
||||
} from '@/lib/redux'
|
||||
import styles from './counter.module.css'
|
||||
|
||||
function Counter() {
|
||||
const dispatch = useAppDispatch()
|
||||
const count = useAppSelector(selectCount)
|
||||
const [incrementAmount, setIncrementAmount] = useState('2')
|
||||
|
||||
const incrementValue = Number(incrementAmount) || 0
|
||||
export const Counter = () => {
|
||||
const dispatch = useDispatch()
|
||||
const count = useSelector(selectCount)
|
||||
const [incrementAmount, setIncrementAmount] = useState(2)
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
@ -24,7 +25,7 @@ function Counter() {
|
|||
<button
|
||||
className={styles.button}
|
||||
aria-label="Decrement value"
|
||||
onClick={() => dispatch(decrement())}
|
||||
onClick={() => dispatch(counterSlice.actions.decrement())}
|
||||
>
|
||||
-
|
||||
</button>
|
||||
|
@ -32,7 +33,7 @@ function Counter() {
|
|||
<button
|
||||
className={styles.button}
|
||||
aria-label="Increment value"
|
||||
onClick={() => dispatch(increment())}
|
||||
onClick={() => dispatch(counterSlice.actions.increment())}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
|
@ -42,23 +43,25 @@ function Counter() {
|
|||
className={styles.textbox}
|
||||
aria-label="Set increment amount"
|
||||
value={incrementAmount}
|
||||
onChange={(e) => setIncrementAmount(e.target.value)}
|
||||
onChange={(e) => setIncrementAmount(Number(e.target.value ?? 0))}
|
||||
/>
|
||||
<button
|
||||
className={styles.button}
|
||||
onClick={() => dispatch(incrementByAmount(incrementValue))}
|
||||
onClick={() =>
|
||||
dispatch(counterSlice.actions.incrementByAmount(incrementAmount))
|
||||
}
|
||||
>
|
||||
Add Amount
|
||||
</button>
|
||||
<button
|
||||
className={styles.asyncButton}
|
||||
onClick={() => dispatch(incrementAsync(incrementValue))}
|
||||
onClick={() => dispatch(incrementAsync(incrementAmount))}
|
||||
>
|
||||
Add Async
|
||||
</button>
|
||||
<button
|
||||
className={styles.button}
|
||||
onClick={() => dispatch(incrementIfOdd(incrementValue))}
|
||||
onClick={() => dispatch(incrementIfOddAsync(incrementAmount))}
|
||||
>
|
||||
Add If Odd
|
||||
</button>
|
||||
|
@ -66,5 +69,3 @@ function Counter() {
|
|||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Counter
|
31
examples/with-redux/app/components/Nav.tsx
Normal file
31
examples/with-redux/app/components/Nav.tsx
Normal file
|
@ -0,0 +1,31 @@
|
|||
'use client'
|
||||
|
||||
/* Core */
|
||||
import Link from 'next/link'
|
||||
import { usePathname } from 'next/navigation'
|
||||
|
||||
/* Instruments */
|
||||
import styles from '../styles/layout.module.css'
|
||||
|
||||
export const Nav = () => {
|
||||
const pathname = usePathname()
|
||||
|
||||
return (
|
||||
<nav className={styles.nav}>
|
||||
<Link
|
||||
className={`${styles.link} ${pathname === '/' ? styles.active : ''}`}
|
||||
href="/"
|
||||
>
|
||||
Home
|
||||
</Link>
|
||||
<Link
|
||||
className={`${styles.link} ${
|
||||
pathname === '/verify' ? styles.active : ''
|
||||
}`}
|
||||
href="/verify"
|
||||
>
|
||||
Verify
|
||||
</Link>
|
||||
</nav>
|
||||
)
|
||||
}
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 3.5 KiB |
66
examples/with-redux/app/layout.tsx
Normal file
66
examples/with-redux/app/layout.tsx
Normal file
|
@ -0,0 +1,66 @@
|
|||
/* Components */
|
||||
import { Providers } from '@/lib/providers'
|
||||
import { Nav } from './components/Nav'
|
||||
|
||||
/* Instruments */
|
||||
import styles from './styles/layout.module.css'
|
||||
import './styles/globals.css'
|
||||
|
||||
export default function RootLayout(props: React.PropsWithChildren) {
|
||||
return (
|
||||
<Providers>
|
||||
<html lang="en">
|
||||
<body>
|
||||
<section className={styles.container}>
|
||||
<Nav />
|
||||
|
||||
<header className={styles.header}>
|
||||
<img src="/logo.svg" className={styles.logo} alt="logo" />
|
||||
</header>
|
||||
|
||||
<main className={styles.main}>{props.children}</main>
|
||||
|
||||
<footer className={styles.footer}>
|
||||
<span>Learn </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://reactjs.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
React
|
||||
</a>
|
||||
<span>, </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://redux.js.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Redux
|
||||
</a>
|
||||
<span>, </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://redux-toolkit.js.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Redux Toolkit
|
||||
</a>
|
||||
,<span> and </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://react-redux.js.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
React Redux
|
||||
</a>
|
||||
</footer>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
</Providers>
|
||||
)
|
||||
}
|
10
examples/with-redux/app/page.tsx
Normal file
10
examples/with-redux/app/page.tsx
Normal file
|
@ -0,0 +1,10 @@
|
|||
/* Components */
|
||||
import { Counter } from './components/Counter/Counter'
|
||||
|
||||
export default function IndexPage() {
|
||||
return <Counter />
|
||||
}
|
||||
|
||||
export const metadata = {
|
||||
title: 'Redux Toolkit',
|
||||
}
|
16
examples/with-redux/app/styles/globals.css
Normal file
16
examples/with-redux/app/styles/globals.css
Normal file
|
@ -0,0 +1,16 @@
|
|||
html,
|
||||
body {
|
||||
min-height: 100vh;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
77
examples/with-redux/app/styles/layout.module.css
Normal file
77
examples/with-redux/app/styles/layout.module.css
Normal file
|
@ -0,0 +1,77 @@
|
|||
.container {
|
||||
display: grid;
|
||||
grid-template-areas:
|
||||
'nav'
|
||||
'header'
|
||||
'main'
|
||||
'footer';
|
||||
grid-template-rows: auto auto 1fr 36px;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.header {
|
||||
grid-area: header;
|
||||
}
|
||||
|
||||
.main {
|
||||
grid-area: main;
|
||||
}
|
||||
|
||||
.header,
|
||||
.main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.footer {
|
||||
grid-area: footer;
|
||||
justify-self: center;
|
||||
}
|
||||
|
||||
.nav {
|
||||
grid-area: nav;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
font-size: calc(10px + 2vmin);
|
||||
}
|
||||
|
||||
.link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.link {
|
||||
color: #704cb6;
|
||||
}
|
||||
|
||||
.link.active {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.logo {
|
||||
animation: logo-float infinite 3s ease-in-out;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes logo-float {
|
||||
0% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(10px);
|
||||
}
|
||||
100% {
|
||||
transform: translateY(0px);
|
||||
}
|
||||
}
|
11
examples/with-redux/app/verify/page.tsx
Normal file
11
examples/with-redux/app/verify/page.tsx
Normal file
|
@ -0,0 +1,11 @@
|
|||
export default function VerifyPage() {
|
||||
return (
|
||||
<>
|
||||
<h1>Verify page</h1>
|
||||
<p>
|
||||
This page is intended to verify that Redux state is persisted across
|
||||
page navigations.
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
import type { InitialOptionsTsJest } from 'ts-jest/dist/types'
|
||||
|
||||
const config: InitialOptionsTsJest = {
|
||||
preset: 'ts-jest',
|
||||
setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],
|
||||
transform: {
|
||||
'.+\\.(css|styl|less|sass|scss)$': 'jest-css-modules-transform',
|
||||
},
|
||||
testEnvironment: 'jsdom',
|
||||
globals: {
|
||||
'ts-jest': {
|
||||
tsconfig: 'tsconfig.test.json',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export default config
|
11
examples/with-redux/lib/providers.tsx
Normal file
11
examples/with-redux/lib/providers.tsx
Normal file
|
@ -0,0 +1,11 @@
|
|||
'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>
|
||||
}
|
14
examples/with-redux/lib/redux/createAppAsyncThunk.ts
Normal file
14
examples/with-redux/lib/redux/createAppAsyncThunk.ts
Normal file
|
@ -0,0 +1,14 @@
|
|||
/* Core */
|
||||
import { createAsyncThunk } from '@reduxjs/toolkit'
|
||||
|
||||
/* Instruments */
|
||||
import type { ReduxState, ReduxDispatch } from './store'
|
||||
|
||||
/**
|
||||
* ? A utility function to create a typed Async Thnuk Actions.
|
||||
*/
|
||||
export const createAppAsyncThunk = createAsyncThunk.withTypes<{
|
||||
state: ReduxState
|
||||
dispatch: ReduxDispatch
|
||||
rejectValue: string
|
||||
}>()
|
2
examples/with-redux/lib/redux/index.ts
Normal file
2
examples/with-redux/lib/redux/index.ts
Normal file
|
@ -0,0 +1,2 @@
|
|||
export * from './store'
|
||||
export * from './slices'
|
20
examples/with-redux/lib/redux/middleware.ts
Normal file
20
examples/with-redux/lib/redux/middleware.ts
Normal file
|
@ -0,0 +1,20 @@
|
|||
/* 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 }
|
6
examples/with-redux/lib/redux/rootReducer.ts
Normal file
6
examples/with-redux/lib/redux/rootReducer.ts
Normal file
|
@ -0,0 +1,6 @@
|
|||
/* Instruments */
|
||||
import { counterSlice } from './slices'
|
||||
|
||||
export const reducer = {
|
||||
counter: counterSlice.reducer,
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
/* 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'
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
export const fetchIdentityCount = async (
|
||||
amount = 1
|
||||
): Promise<{ data: number }> => {
|
||||
const response = await fetch('http://localhost:3000/api/identity-count', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ amount }),
|
||||
})
|
||||
const result = await response.json()
|
||||
|
||||
return result
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
export * from './counterSlice'
|
||||
export * from './thunks'
|
||||
export * from './selectors'
|
|
@ -0,0 +1,7 @@
|
|||
/* 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
|
33
examples/with-redux/lib/redux/slices/counterSlice/thunks.ts
Normal file
33
examples/with-redux/lib/redux/slices/counterSlice/thunks.ts
Normal file
|
@ -0,0 +1,33 @@
|
|||
/* 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))
|
||||
}
|
||||
}
|
1
examples/with-redux/lib/redux/slices/index.ts
Normal file
1
examples/with-redux/lib/redux/slices/index.ts
Normal file
|
@ -0,0 +1 @@
|
|||
export * from './counterSlice'
|
46
examples/with-redux/lib/redux/store.ts
Normal file
46
examples/with-redux/lib/redux/store.ts
Normal file
|
@ -0,0 +1,46 @@
|
|||
/* Core */
|
||||
import {
|
||||
configureStore,
|
||||
type ConfigureStoreOptions,
|
||||
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'
|
||||
|
||||
const configreStoreDefaultOptions: ConfigureStoreOptions = { reducer }
|
||||
|
||||
export const makeReduxStore = (
|
||||
options: ConfigureStoreOptions = configreStoreDefaultOptions
|
||||
) => {
|
||||
const store = configureStore(options)
|
||||
|
||||
return store
|
||||
}
|
||||
|
||||
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
|
||||
>
|
6
examples/with-redux/next.config.mjs
Normal file
6
examples/with-redux/next.config.mjs
Normal file
|
@ -0,0 +1,6 @@
|
|||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
}
|
||||
|
||||
export default nextConfig
|
|
@ -3,30 +3,21 @@
|
|||
"scripts": {
|
||||
"dev": "next",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"type-check": "tsc",
|
||||
"test": "jest"
|
||||
"start": "next start"
|
||||
},
|
||||
"dependencies": {
|
||||
"@reduxjs/toolkit": "^1.3.6",
|
||||
"@reduxjs/toolkit": "1.9.5",
|
||||
"next": "latest",
|
||||
"react": "^18.1.0",
|
||||
"react-dom": "^18.1.0",
|
||||
"react-redux": "^7.2.0"
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
"react-redux": "8.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^5.0.0",
|
||||
"@testing-library/react": "^14.0.0",
|
||||
"@testing-library/user-event": "^13.0.0",
|
||||
"@types/jest": "^27.0.1",
|
||||
"@types/node": "^16.9.1",
|
||||
"@types/react": "^18.0.10",
|
||||
"@types/react-dom": "^18.0.5",
|
||||
"@types/react-redux": "^7.1.18",
|
||||
"jest": "^27.2.0",
|
||||
"jest-css-modules-transform": "^4.2.0",
|
||||
"ts-jest": "^27.0.5",
|
||||
"ts-node": "^10.2.1",
|
||||
"typescript": "^4.3.4"
|
||||
"@types/node": "20.3.1",
|
||||
"@types/react": "18.2.12",
|
||||
"@types/react-dom": "18.2.5",
|
||||
"@types/redux-logger": "3.0.9",
|
||||
"redux-logger": "3.0.6",
|
||||
"typescript": "5.1.3"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
import '@testing-library/jest-dom'
|
||||
import { loadEnvConfig } from '@next/env'
|
||||
|
||||
loadEnvConfig(__dirname, true, { info: () => null, error: console.error })
|
|
@ -1,105 +0,0 @@
|
|||
import { render, screen } from '@testing-library/react'
|
||||
import user from '@testing-library/user-event'
|
||||
import { Provider } from 'react-redux'
|
||||
|
||||
jest.mock('./counterAPI', () => ({
|
||||
fetchCount: (amount: number) =>
|
||||
new Promise<{ data: number }>((resolve) =>
|
||||
setTimeout(() => resolve({ data: amount }), 500)
|
||||
),
|
||||
}))
|
||||
|
||||
import { makeStore } from '../../store'
|
||||
import Counter from './Counter'
|
||||
|
||||
describe('<Counter />', () => {
|
||||
it('renders the component', () => {
|
||||
const store = makeStore()
|
||||
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<Counter />
|
||||
</Provider>
|
||||
)
|
||||
|
||||
expect(screen.getByText('0')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('decrements the value', () => {
|
||||
const store = makeStore()
|
||||
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<Counter />
|
||||
</Provider>
|
||||
)
|
||||
|
||||
user.click(screen.getByRole('button', { name: /decrement value/i }))
|
||||
|
||||
expect(screen.getByText('-1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('increments the value', () => {
|
||||
const store = makeStore()
|
||||
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<Counter />
|
||||
</Provider>
|
||||
)
|
||||
|
||||
user.click(screen.getByRole('button', { name: /increment value/i }))
|
||||
|
||||
expect(screen.getByText('1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('increments by amount', () => {
|
||||
const store = makeStore()
|
||||
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<Counter />
|
||||
</Provider>
|
||||
)
|
||||
|
||||
user.type(screen.getByLabelText(/set increment amount/i), '{backspace}5')
|
||||
user.click(screen.getByRole('button', { name: /add amount/i }))
|
||||
|
||||
expect(screen.getByText('5')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('increments async', async () => {
|
||||
const store = makeStore()
|
||||
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<Counter />
|
||||
</Provider>
|
||||
)
|
||||
|
||||
user.type(screen.getByLabelText(/set increment amount/i), '{backspace}3')
|
||||
user.click(screen.getByRole('button', { name: /add async/i }))
|
||||
|
||||
await expect(screen.findByText('3')).resolves.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('increments if amount is odd', async () => {
|
||||
const store = makeStore()
|
||||
|
||||
render(
|
||||
<Provider store={store}>
|
||||
<Counter />
|
||||
</Provider>
|
||||
)
|
||||
|
||||
user.click(screen.getByRole('button', { name: /add if odd/i }))
|
||||
|
||||
expect(screen.getByText('0')).toBeInTheDocument()
|
||||
|
||||
user.click(screen.getByRole('button', { name: /increment value/i }))
|
||||
user.type(screen.getByLabelText(/set increment amount/i), '{backspace}8')
|
||||
user.click(screen.getByRole('button', { name: /add if odd/i }))
|
||||
|
||||
await expect(screen.findByText('9')).resolves.toBeInTheDocument()
|
||||
})
|
||||
})
|
|
@ -1,12 +0,0 @@
|
|||
export async function fetchCount(amount = 1): Promise<{ data: number }> {
|
||||
const response = await fetch('/api/counter', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ amount }),
|
||||
})
|
||||
const result = await response.json()
|
||||
|
||||
return result
|
||||
}
|
|
@ -1,82 +0,0 @@
|
|||
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
|
||||
import type { AppState, AppThunk } from '../../store'
|
||||
import { fetchCount } from './counterAPI'
|
||||
|
||||
export interface CounterState {
|
||||
value: number
|
||||
status: 'idle' | 'loading' | 'failed'
|
||||
}
|
||||
|
||||
const initialState: CounterState = {
|
||||
value: 0,
|
||||
status: 'idle',
|
||||
}
|
||||
|
||||
// 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 = createAsyncThunk(
|
||||
'counter/fetchCount',
|
||||
async (amount: number) => {
|
||||
const response = await fetchCount(amount)
|
||||
// The value we return becomes the `fulfilled` action payload
|
||||
return response.data
|
||||
}
|
||||
)
|
||||
|
||||
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
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const { increment, decrement, incrementByAmount } = counterSlice.actions
|
||||
|
||||
// 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: AppState) => state.counter.value
|
||||
|
||||
// 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) {
|
||||
dispatch(incrementByAmount(amount))
|
||||
}
|
||||
}
|
||||
|
||||
export default counterSlice.reducer
|
|
@ -1,48 +0,0 @@
|
|||
import type { ChangeEvent } from 'react'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
|
||||
|
||||
import type { AppDispatch, AppState } from './store'
|
||||
|
||||
export const useForm =
|
||||
<TContent>(defaultValues: TContent) =>
|
||||
(handler: (content: TContent) => void) =>
|
||||
async (event: ChangeEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
event.persist()
|
||||
|
||||
const form = event.target as HTMLFormElement
|
||||
const elements = Array.from(form.elements) as HTMLInputElement[]
|
||||
const data = elements
|
||||
.filter((element) => element.hasAttribute('name'))
|
||||
.reduce(
|
||||
(object, element) => ({
|
||||
...object,
|
||||
[`${element.getAttribute('name')}`]: element.value,
|
||||
}),
|
||||
defaultValues
|
||||
)
|
||||
await handler(data)
|
||||
form.reset()
|
||||
}
|
||||
|
||||
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
|
||||
export const useInterval = (callback: Function, delay: number) => {
|
||||
const savedCallback = useRef<Function>()
|
||||
useEffect(() => {
|
||||
savedCallback.current = callback
|
||||
}, [callback])
|
||||
useEffect(() => {
|
||||
const handler = (...args: any) => savedCallback.current?.(...args)
|
||||
|
||||
if (delay !== null) {
|
||||
const id = setInterval(handler, delay)
|
||||
return () => clearInterval(id)
|
||||
}
|
||||
}, [delay])
|
||||
}
|
||||
|
||||
// Use throughout your app instead of plain `useDispatch` and `useSelector`
|
||||
export const useAppDispatch = () => useDispatch<AppDispatch>()
|
||||
|
||||
export const useAppSelector: TypedUseSelectorHook<AppState> = useSelector
|
|
@ -1,14 +0,0 @@
|
|||
import '../styles/globals.css'
|
||||
|
||||
import { Provider } from 'react-redux'
|
||||
import type { AppProps } from 'next/app'
|
||||
|
||||
import store from '../store'
|
||||
|
||||
export default function MyApp({ Component, pageProps }: AppProps) {
|
||||
return (
|
||||
<Provider store={store}>
|
||||
<Component {...pageProps} />
|
||||
</Provider>
|
||||
)
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
import type { NextApiHandler } from 'next'
|
||||
|
||||
const countHandler: NextApiHandler = async (request, response) => {
|
||||
const { amount = 1 } = request.body
|
||||
|
||||
// simulate IO latency
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
|
||||
response.json({ data: amount })
|
||||
}
|
||||
|
||||
export default countHandler
|
|
@ -1,63 +0,0 @@
|
|||
import type { NextPage } from 'next'
|
||||
import Head from 'next/head'
|
||||
|
||||
import Counter from '../features/counter/Counter'
|
||||
import styles from '../styles/Home.module.css'
|
||||
|
||||
const IndexPage: NextPage = () => {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<Head>
|
||||
<title>Redux Toolkit</title>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<header className={styles.header}>
|
||||
<img src="/logo.svg" className={styles.logo} alt="logo" />
|
||||
<Counter />
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to reload.
|
||||
</p>
|
||||
<span>
|
||||
<span>Learn </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://reactjs.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
React
|
||||
</a>
|
||||
<span>, </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://redux.js.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Redux
|
||||
</a>
|
||||
<span>, </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://redux-toolkit.js.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Redux Toolkit
|
||||
</a>
|
||||
,<span> and </span>
|
||||
<a
|
||||
className={styles.link}
|
||||
href="https://react-redux.js.org/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
React Redux
|
||||
</a>
|
||||
</span>
|
||||
</header>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default IndexPage
|
|
@ -1,24 +0,0 @@
|
|||
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'
|
||||
|
||||
import counterReducer from './features/counter/counterSlice'
|
||||
|
||||
export function makeStore() {
|
||||
return configureStore({
|
||||
reducer: { counter: counterReducer },
|
||||
})
|
||||
}
|
||||
|
||||
const store = makeStore()
|
||||
|
||||
export type AppState = ReturnType<typeof store.getState>
|
||||
|
||||
export type AppDispatch = typeof store.dispatch
|
||||
|
||||
export type AppThunk<ReturnType = void> = ThunkAction<
|
||||
ReturnType,
|
||||
AppState,
|
||||
unknown,
|
||||
Action<string>
|
||||
>
|
||||
|
||||
export default store
|
|
@ -1,39 +0,0 @@
|
|||
.container {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.header {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
}
|
||||
|
||||
.link {
|
||||
color: rgb(112, 76, 182);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.logo {
|
||||
animation: logo-float infinite 3s ease-in-out;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes logo-float {
|
||||
0% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(10px);
|
||||
}
|
||||
100% {
|
||||
transform: translateY(0px);
|
||||
}
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
html,
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
|
||||
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
|
@ -1,19 +1,24 @@
|
|||
{
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"baseUrl": ".",
|
||||
"paths": { "@/*": ["./*"] },
|
||||
"target": "ESNext",
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"module": "ESNEXT",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve"
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }]
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx"
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue