Skip to content

Commit 8e4123e

Browse files
authored
feat: add exemple with redux toolkit in typescript (#23250)
This pull request add typescript to the current redux-toolkit example on next.js. @markerikson suggested this nice idea to add a ts example: https://twitter.com/acemarke/status/1370877104527712259?s=20 This example is with the previous redux-toolkit example which was more complex. An example with the current example is available here: #23249 ## Bug - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added ## Feature - [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. ## Documentation / Examples - [ ] Make sure the linting passes
1 parent 46fc696 commit 8e4123e

File tree

21 files changed

+976
-0
lines changed

21 files changed

+976
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# next.js
12+
/.next/
13+
/out/
14+
15+
# production
16+
/build
17+
18+
# misc
19+
.DS_Store
20+
*.pem
21+
22+
# debug
23+
npm-debug.log*
24+
yarn-debug.log*
25+
yarn-error.log*
26+
27+
# local env files
28+
.env.local
29+
.env.development.local
30+
.env.test.local
31+
.env.production.local
32+
33+
# vercel
34+
.vercel
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Redux Toolkit TypeScript Example
2+
3+
This example shows how to integrate Next.js with [Redux Toolkit](https://redux-toolkit.js.org).
4+
5+
The **Redux Toolkit** is intended to be the standard 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
6+
7+
## Deploy your own
8+
9+
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
10+
11+
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-redux-toolkit-typescript&project-name=with-redux-toolkit&repository-name=with-redux-toolkit)
12+
13+
## How to use
14+
15+
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
16+
17+
```bash
18+
npx create-next-app --example with-redux-toolkit-typescript with-redux-toolkit-app
19+
# or
20+
yarn create next-app --example with-redux-toolkit-typescript with-redux-toolkit-app
21+
```
22+
23+
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { FC } from 'react'
2+
import { useDispatch, useSelector } from 'react-redux'
3+
4+
import { addNote, selectNotes } from '../lib/slices/notesSlice'
5+
import useForm from '../lib/useForm'
6+
import { Note } from '../types/Note'
7+
import { isErrorResponse } from '../types/ErrorResponse'
8+
9+
const AddNoteForm: FC = () => {
10+
const dispatch = useDispatch()
11+
const { error } = useSelector(selectNotes)
12+
const handleSubmit = useForm<Note>({
13+
title: '',
14+
content: '',
15+
})
16+
17+
return (
18+
<form onSubmit={handleSubmit((data) => dispatch(addNote(data)))}>
19+
<h3>Create a Note</h3>
20+
<label htmlFor="titleText">
21+
Title:
22+
<input type="text" name="title" id="titleText" />
23+
</label>
24+
<br />
25+
{isErrorResponse(error) && <small>{error.title}</small>}
26+
<br />
27+
<label htmlFor="contentText">
28+
Content:
29+
<textarea name="content" id="contentText" />
30+
</label>
31+
<br />
32+
{isErrorResponse(error) && <small>{error.content}</small>}
33+
<br />
34+
<button type="submit">Add note</button>
35+
<br />
36+
{!isErrorResponse(error) && <small>{error}</small>}
37+
</form>
38+
)
39+
}
40+
41+
export default AddNoteForm
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { FC } from 'react'
2+
import { useSelector } from 'react-redux'
3+
4+
import { selectClock } from '../lib/slices/clockSlice'
5+
6+
const formatTime = (time: number) => {
7+
// cut off except hh:mm:ss
8+
return new Date(time).toJSON().slice(11, 19)
9+
}
10+
11+
const Clock: FC = () => {
12+
const { lastUpdate, light } = useSelector(selectClock)
13+
14+
return (
15+
<div className={light ? 'light' : ''}>
16+
{formatTime(lastUpdate)}
17+
<style jsx>{`
18+
div {
19+
padding: 15px;
20+
display: inline-block;
21+
color: #82fa58;
22+
font: 50px menlo, monaco, monospace;
23+
background-color: #000;
24+
}
25+
26+
.light {
27+
background-color: #999;
28+
}
29+
`}</style>
30+
</div>
31+
)
32+
}
33+
34+
export default Clock
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
import { ChangeEvent, FC } from 'react'
2+
import { useState } from 'react'
3+
import { useDispatch, useSelector } from 'react-redux'
4+
5+
import {
6+
decrement,
7+
increment,
8+
incrementAsync,
9+
incrementByAmount,
10+
reset,
11+
selectCount,
12+
} from '../lib/slices/counterSlice'
13+
14+
const Counter: FC = () => {
15+
const dispatch = useDispatch()
16+
const count = useSelector(selectCount)
17+
const [incrementAmount, setIncrementAmount] = useState('2')
18+
19+
function dispatchIncrement() {
20+
dispatch(increment())
21+
}
22+
function dispatchDecrement() {
23+
dispatch(decrement())
24+
}
25+
function dispatchReset() {
26+
dispatch(reset())
27+
}
28+
function changeIncrementAmount(event: ChangeEvent<HTMLInputElement>) {
29+
setIncrementAmount(event.target.value)
30+
}
31+
function dispatchIncrementByAmount() {
32+
dispatch(incrementByAmount(Number(incrementAmount) || 0))
33+
}
34+
function dispatchIncrementAsync() {
35+
dispatch(incrementAsync(Number(incrementAmount) || 0))
36+
}
37+
38+
return (
39+
<>
40+
<div className="row">
41+
<button
42+
className="button"
43+
aria-label="Increment value"
44+
onClick={dispatchIncrement}
45+
>
46+
+
47+
</button>
48+
<span className="value">{count}</span>
49+
<button
50+
className="button"
51+
aria-label="Decrement value"
52+
onClick={dispatchDecrement}
53+
>
54+
-
55+
</button>
56+
</div>
57+
<div className="row">
58+
<input
59+
className="textbox"
60+
aria-label="Set increment amount"
61+
value={incrementAmount}
62+
onChange={changeIncrementAmount}
63+
/>
64+
<button className="button" onClick={dispatchIncrementByAmount}>
65+
Add Amount
66+
</button>
67+
<button className="button asyncButton" onClick={dispatchIncrementAsync}>
68+
Add Async
69+
</button>
70+
</div>
71+
<div className="row">
72+
<button className="button" onClick={dispatchReset}>
73+
Reset
74+
</button>
75+
</div>
76+
<style jsx>{`
77+
.row {
78+
display: flex;
79+
align-items: center;
80+
justify-content: center;
81+
}
82+
83+
.row:not(:last-child) {
84+
margin-bottom: 16px;
85+
}
86+
87+
.value {
88+
font-size: 78px;
89+
padding-left: 16px;
90+
padding-right: 16px;
91+
margin-top: 2px;
92+
font-family: 'Courier New', Courier, monospace;
93+
}
94+
95+
.button {
96+
appearance: none;
97+
background: none;
98+
font-size: 32px;
99+
padding-left: 12px;
100+
padding-right: 12px;
101+
outline: none;
102+
border: 2px solid transparent;
103+
color: rgb(112, 76, 182);
104+
padding-bottom: 4px;
105+
cursor: pointer;
106+
background-color: rgba(112, 76, 182, 0.1);
107+
border-radius: 2px;
108+
transition: all 0.15s;
109+
}
110+
111+
.textbox {
112+
font-size: 32px;
113+
padding: 2px;
114+
width: 64px;
115+
text-align: center;
116+
margin-right: 8px;
117+
}
118+
119+
.button:hover,
120+
.button:focus {
121+
border: 2px solid rgba(112, 76, 182, 0.4);
122+
}
123+
124+
.button:active {
125+
background-color: rgba(112, 76, 182, 0.2);
126+
}
127+
128+
.asyncButton {
129+
position: relative;
130+
margin-left: 8px;
131+
}
132+
133+
.asyncButton:after {
134+
content: '';
135+
background-color: rgba(112, 76, 182, 0.15);
136+
display: block;
137+
position: absolute;
138+
width: 100%;
139+
height: 100%;
140+
left: 0;
141+
top: 0;
142+
opacity: 0;
143+
transition: width 1s linear, opacity 0.5s ease 1s;
144+
}
145+
146+
.asyncButton:active:after {
147+
width: 0%;
148+
opacity: 1;
149+
transition: 0s;
150+
}
151+
`}</style>
152+
</>
153+
)
154+
}
155+
156+
export default Counter
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { FC } from 'react'
2+
import { useLayoutEffect, useRef } from 'react'
3+
import { useDispatch } from 'react-redux'
4+
5+
import { editNote } from '../lib/slices/notesSlice'
6+
import useForm from '../lib/useForm'
7+
import { PersistedNote } from '../types/Note'
8+
9+
type Props = {
10+
note: PersistedNote
11+
}
12+
13+
const EditNoteForm: FC<Props> = ({ note }) => {
14+
const dialogRef = useRef<HTMLDialogElement>(null)
15+
const dispatch = useDispatch()
16+
const handleSubmit = useForm<PersistedNote>(note)
17+
18+
useLayoutEffect(() => {
19+
const isOpen = Object.keys(note).length > 0
20+
if (isOpen) {
21+
dialogRef.current?.setAttribute('open', 'true')
22+
}
23+
}, [note])
24+
25+
return (
26+
<dialog ref={dialogRef}>
27+
<form
28+
onSubmit={handleSubmit(async (data) => {
29+
await dispatch(editNote(data))
30+
dialogRef.current?.removeAttribute('open')
31+
})}
32+
>
33+
<h3>Edit Note</h3>
34+
<label htmlFor="titleInput">
35+
Title:
36+
<input
37+
type="text"
38+
name="title"
39+
id="titleInput"
40+
defaultValue={note.title}
41+
/>
42+
</label>
43+
<br />
44+
<label htmlFor="contentInput">
45+
Content:
46+
<textarea
47+
name="content"
48+
id="contentInput"
49+
defaultValue={note.content}
50+
/>
51+
</label>
52+
<br />
53+
<button type="submit">Edit</button>
54+
<br />
55+
</form>
56+
</dialog>
57+
)
58+
}
59+
60+
export default EditNoteForm
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
2+
import { CoreState } from '../../src/store'
3+
4+
type ClockState = {
5+
lastUpdate: number
6+
light: boolean
7+
}
8+
9+
const initialState: ClockState = {
10+
lastUpdate: 0,
11+
light: true,
12+
}
13+
14+
const clockSlice = createSlice({
15+
name: 'clock',
16+
initialState,
17+
reducers: {
18+
tick: (state, action: PayloadAction<ClockState>) => {
19+
state.lastUpdate = action.payload.lastUpdate
20+
state.light = !!action.payload.light
21+
},
22+
},
23+
})
24+
25+
export const selectClock = (state: CoreState) => state.clock
26+
27+
export const { tick } = clockSlice.actions
28+
29+
export default clockSlice.reducer

0 commit comments

Comments
 (0)