Unverified Commit 8e4123e9 authored by Julien Karst's avatar Julien Karst Committed by GitHub

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: https://github.com/vercel/next.js/pull/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
parent 46fc6968
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# Redux Toolkit TypeScript Example
This example shows how to integrate Next.js with [Redux Toolkit](https://redux-toolkit.js.org).
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
## 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/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)
## 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) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example with-redux-toolkit-typescript with-redux-toolkit-app
# or
yarn create next-app --example with-redux-toolkit-typescript with-redux-toolkit-app
```
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)).
import { FC } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { addNote, selectNotes } from '../lib/slices/notesSlice'
import useForm from '../lib/useForm'
import { Note } from '../types/Note'
import { isErrorResponse } from '../types/ErrorResponse'
const AddNoteForm: FC = () => {
const dispatch = useDispatch()
const { error } = useSelector(selectNotes)
const handleSubmit = useForm<Note>({
title: '',
content: '',
})
return (
<form onSubmit={handleSubmit((data) => dispatch(addNote(data)))}>
<h3>Create a Note</h3>
<label htmlFor="titleText">
Title:
<input type="text" name="title" id="titleText" />
</label>
<br />
{isErrorResponse(error) && <small>{error.title}</small>}
<br />
<label htmlFor="contentText">
Content:
<textarea name="content" id="contentText" />
</label>
<br />
{isErrorResponse(error) && <small>{error.content}</small>}
<br />
<button type="submit">Add note</button>
<br />
{!isErrorResponse(error) && <small>{error}</small>}
</form>
)
}
export default AddNoteForm
import { FC } from 'react'
import { useSelector } from 'react-redux'
import { selectClock } from '../lib/slices/clockSlice'
const formatTime = (time: number) => {
// cut off except hh:mm:ss
return new Date(time).toJSON().slice(11, 19)
}
const Clock: FC = () => {
const { lastUpdate, light } = useSelector(selectClock)
return (
<div className={light ? 'light' : ''}>
{formatTime(lastUpdate)}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82fa58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div>
)
}
export default Clock
import { ChangeEvent, FC } from 'react'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
decrement,
increment,
incrementAsync,
incrementByAmount,
reset,
selectCount,
} from '../lib/slices/counterSlice'
const Counter: FC = () => {
const dispatch = useDispatch()
const count = useSelector(selectCount)
const [incrementAmount, setIncrementAmount] = useState('2')
function dispatchIncrement() {
dispatch(increment())
}
function dispatchDecrement() {
dispatch(decrement())
}
function dispatchReset() {
dispatch(reset())
}
function changeIncrementAmount(event: ChangeEvent<HTMLInputElement>) {
setIncrementAmount(event.target.value)
}
function dispatchIncrementByAmount() {
dispatch(incrementByAmount(Number(incrementAmount) || 0))
}
function dispatchIncrementAsync() {
dispatch(incrementAsync(Number(incrementAmount) || 0))
}
return (
<>
<div className="row">
<button
className="button"
aria-label="Increment value"
onClick={dispatchIncrement}
>
+
</button>
<span className="value">{count}</span>
<button
className="button"
aria-label="Decrement value"
onClick={dispatchDecrement}
>
-
</button>
</div>
<div className="row">
<input
className="textbox"
aria-label="Set increment amount"
value={incrementAmount}
onChange={changeIncrementAmount}
/>
<button className="button" onClick={dispatchIncrementByAmount}>
Add Amount
</button>
<button className="button asyncButton" onClick={dispatchIncrementAsync}>
Add Async
</button>
</div>
<div className="row">
<button className="button" onClick={dispatchReset}>
Reset
</button>
</div>
<style jsx>{`
.row {
display: flex;
align-items: center;
justify-content: center;
}
.row:not(:last-child) {
margin-bottom: 16px;
}
.value {
font-size: 78px;
padding-left: 16px;
padding-right: 16px;
margin-top: 2px;
font-family: 'Courier New', Courier, monospace;
}
.button {
appearance: none;
background: none;
font-size: 32px;
padding-left: 12px;
padding-right: 12px;
outline: none;
border: 2px solid transparent;
color: rgb(112, 76, 182);
padding-bottom: 4px;
cursor: pointer;
background-color: rgba(112, 76, 182, 0.1);
border-radius: 2px;
transition: all 0.15s;
}
.textbox {
font-size: 32px;
padding: 2px;
width: 64px;
text-align: center;
margin-right: 8px;
}
.button:hover,
.button:focus {
border: 2px solid rgba(112, 76, 182, 0.4);
}
.button:active {
background-color: rgba(112, 76, 182, 0.2);
}
.asyncButton {
position: relative;
margin-left: 8px;
}
.asyncButton:after {
content: '';
background-color: rgba(112, 76, 182, 0.15);
display: block;
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
opacity: 0;
transition: width 1s linear, opacity 0.5s ease 1s;
}
.asyncButton:active:after {
width: 0%;
opacity: 1;
transition: 0s;
}
`}</style>
</>
)
}
export default Counter
import { FC } from 'react'
import { useLayoutEffect, useRef } from 'react'
import { useDispatch } from 'react-redux'
import { editNote } from '../lib/slices/notesSlice'
import useForm from '../lib/useForm'
import { PersistedNote } from '../types/Note'
type Props = {
note: PersistedNote
}
const EditNoteForm: FC<Props> = ({ note }) => {
const dialogRef = useRef<HTMLDialogElement>(null)
const dispatch = useDispatch()
const handleSubmit = useForm<PersistedNote>(note)
useLayoutEffect(() => {
const isOpen = Object.keys(note).length > 0
if (isOpen) {
dialogRef.current?.setAttribute('open', 'true')
}
}, [note])
return (
<dialog ref={dialogRef}>
<form
onSubmit={handleSubmit(async (data) => {
await dispatch(editNote(data))
dialogRef.current?.removeAttribute('open')
})}
>
<h3>Edit Note</h3>
<label htmlFor="titleInput">
Title:
<input
type="text"
name="title"
id="titleInput"
defaultValue={note.title}
/>
</label>
<br />
<label htmlFor="contentInput">
Content:
<textarea
name="content"
id="contentInput"
defaultValue={note.content}
/>
</label>
<br />
<button type="submit">Edit</button>
<br />
</form>
</dialog>
)
}
export default EditNoteForm
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { CoreState } from '../../src/store'
type ClockState = {
lastUpdate: number
light: boolean
}
const initialState: ClockState = {
lastUpdate: 0,
light: true,
}
const clockSlice = createSlice({
name: 'clock',
initialState,
reducers: {
tick: (state, action: PayloadAction<ClockState>) => {
state.lastUpdate = action.payload.lastUpdate
state.light = !!action.payload.light
},
},
})
export const selectClock = (state: CoreState) => state.clock
export const { tick } = clockSlice.actions
export default clockSlice.reducer
import { createSlice, Dispatch } from '@reduxjs/toolkit'
import { CoreState } from '../../src/store'
type CounterState = {
value: number
}
const initialState: CounterState = {
value: 0,
}
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
// 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
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
reset: (state) => {
state.value = 0
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
/**
* Extract count from root state
*
* @param {Object} state The root state
* @returns {number} The current count
*/
export const selectCount = (state: CoreState) => state.counter.value
export const {
increment,
decrement,
reset,
incrementByAmount,
} = counterSlice.actions
// 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
export const incrementAsync = (amount: number) => (dispatch: Dispatch) => {
setTimeout(() => {
dispatch(incrementByAmount(amount))
}, 1000)
}
export default counterSlice.reducer
import { createAsyncThunk, createSelector, createSlice } from '@reduxjs/toolkit'
import { Note, PersistedNote } from '../../types/Note'
import { CoreState } from '../../src/store'
import { ErrorResponse } from '../../types/ErrorResponse'
type ErrorResult = {
error: ErrorResponse | string
}
type ThunkConfig = { rejectValue: ErrorResult }
export const addNote = createAsyncThunk<PersistedNote, Note, ThunkConfig>(
'notes/addNote',
async (newNote: Note, thunkAPI) => {
try {
const response = await fetch('/api/notes', {
method: 'POST',
body: JSON.stringify(newNote),
headers: {
'Content-Type': 'application/json',
},
})
if (!response.ok) {
const error = await response.json()
return thunkAPI.rejectWithValue({ error: error.errors })
}
return response.json()
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message })
}
}
)
export const loadNotes = createAsyncThunk<PersistedNote[], void, ThunkConfig>(
'notes/loadNotes',
async (_, thunkAPI) => {
try {
const response = await fetch('/api/notes')
return response.json()
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message })
}
}
)
export const editNote = createAsyncThunk<
PersistedNote,
PersistedNote,
ThunkConfig
>('notes/editNote', async (updates, thunkAPI) => {
const { id, title, content } = updates
try {
const response = await fetch(`/api/notes?noteId=${id}`, {
method: 'PUT',
body: JSON.stringify({ title, content }),
headers: {
'Content-Type': 'application/json',
},
})
return response.json()
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message })
}
})
export const deleteNote = createAsyncThunk<string, string, ThunkConfig>(
'notes/deleteNote',
async (id, thunkAPI) => {
try {
await fetch(`/api/notes?noteId=${id}`, { method: 'DELETE' })
return id
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message })
}
}
)
enum LoadingState {
IDLE = 'idle',
LOADING = 'loading',
LOADED = 'loaded',
ERROR = 'error',
}
type NoteState = {
notes: PersistedNote[]
loading: LoadingState
error?: ErrorResponse | string
tempNote?: PersistedNote
backupNote?: PersistedNote
backupPosition?: number
}
const initialState: NoteState = {
notes: [],
loading: LoadingState.IDLE,
error: undefined,
tempNote: undefined,
backupNote: undefined,
backupPosition: undefined,
}
const notesSlice = createSlice({
name: 'notes',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(addNote.pending, (state) => {
delete state.error
})
builder.addCase(addNote.fulfilled, (state, action) => {
state.notes.push(action.payload)
})
builder.addCase(addNote.rejected, (state, action) => {
state.error = action.payload?.error
})
builder.addCase(loadNotes.pending, (state) => {
state.notes = []
state.loading = LoadingState.LOADING
})
builder.addCase(loadNotes.fulfilled, (state, action) => {
state.notes = action.payload
state.loading = LoadingState.LOADED
})
builder.addCase(loadNotes.rejected, (state, action) => {
state.loading = LoadingState.ERROR
state.error = action.payload?.error
})
builder.addCase(editNote.pending, (state, action) => {
const note = state.notes.find((note) => note.id === action.meta.arg.id)
if (!note) return
state.tempNote = Object.assign({}, note)
note.title = action.meta.arg.title || note.title
note.content = action.meta.arg.content || note.content
})
builder.addCase(editNote.fulfilled, (state, action) => {
const note = state.notes.find((note) => note.id === action.payload.id)
delete state.tempNote
Object.assign(note, action.payload)
})
builder.addCase(editNote.rejected, (state, action) => {
const note = state.notes.find((note) => note.id === action.meta.arg.id)
state.error = action.payload?.error || action.error.message
Object.assign(note, state.tempNote)
delete state.tempNote
})
builder.addCase(deleteNote.pending, (state, action) => {
const position = state.notes.findIndex(
(note) => note.id === action.meta.arg
)
state.backupNote = Object.assign({}, state.notes[position])
state.backupPosition = position
state.notes.splice(position, 1)
})
builder.addCase(deleteNote.fulfilled, (state) => {
delete state.backupNote
delete state.backupPosition
})
builder.addCase(deleteNote.rejected, (state) => {
if (!state.backupPosition || !state.backupNote) return
state.notes.splice(state.backupPosition, 0, state.backupNote)
delete state.backupPosition
delete state.backupNote
})
},
})
export const selectNotes = createSelector(
(state: CoreState) => ({
notes: state.notes.notes,
error: state.notes.error,
}),
(state) => state
)
export default notesSlice.reducer
import { ChangeEvent } from 'react'
const useForm = <TContent>(defaultValues: TContent) => (
handler: (content: TContent) => void
) => async (event: ChangeEvent<HTMLFormElement>) => {
event.preventDefault()
event.persist()
const form = event.target
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()
}
export default useForm
import { useEffect, useRef } from 'react'
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
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])
}
export default useInterval
/// <reference types="next" />
/// <reference types="next/types/global" />
{
"name": "with-redux-toolkit-typescript",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"type-check": "tsc"
},
"dependencies": {
"@nano-sql/core": "^2.3.7",
"@reduxjs/toolkit": "^1.3.6",
"next": "latest",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-redux": "^7.2.0"
},
"license": "MIT",
"devDependencies": {
"@types/node": "14.14.35",
"@types/react": "17.0.3",
"@types/react-dom": "17.0.2",
"@types/react-redux": "7.1.16",
"prettier": "2.2.1",
"typescript": "4.2.3"
}
}
import React, { ComponentType } from 'react'
import { Provider } from 'react-redux'
import { AppInitialProps } from 'next/app'
import store from '../src/store'
const MyApp = ({
Component,
pageProps,
}: {
Component: ComponentType<AppInitialProps>
pageProps: AppInitialProps
}) => {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
export default MyApp
import { nSQL } from '@nano-sql/core'
const connectMiddleware = (handler) => async (req, res) => {
const dbName = 'with-redux-toolkit'
if (!nSQL().listDatabases().includes(dbName)) {
await nSQL().createDatabase({
id: dbName,
mode: 'PERM',
tables: [
{
name: 'notes',
model: {
'id:uuid': { pk: true },
'title:string': { notNull: true },
'content:string': { notNull: true },
'createdAt:date': { default: () => new Date() },
},
},
],
version: 1,
})
}
nSQL().useDatabase(dbName)
return handler(req, res)
}
const saveNote = async (req, res) => {
const { title, content } = req.body
const errors = {}
if (!title) errors['title'] = 'Title is required'
if (!content) errors['content'] = 'Content is required'
if (Object.keys(errors).length > 0)
return res.status(422).json({
statusCode: 422,
message: 'Unprocessable Entity',
errors,
})
const [note] = await nSQL('notes').query('upsert', { title, content }).exec()
res.status(201).json(note)
}
const listNotes = async (_, res) => {
const notes = await nSQL('notes').query('select').exec()
res.json(notes)
}
const updateNote = async (req, res) => {
const { noteId } = req.query
const [note] = await nSQL()
.query('select')
.where(['id', '=', noteId])
.limit(1)
.exec()
if (!note)
return res.status(404).json({
statusCode: 404,
message: 'Not Found',
})
const { title = note.title, content = note.content } = req.body
const [noteUpdated] = await nSQL('notes')
.query('upsert', { title, content })
.where(['id', '=', noteId])
.limit(1)
.exec()
res.json(noteUpdated)
}
const removeNote = async (req, res) => {
const { noteId } = req.query
const [note] = await nSQL()
.query('select')
.where(['id', '=', noteId])
.limit(1)
.exec()
if (!note)
return res.status(404).json({
statusCode: 404,
message: 'Not Found',
})
await nSQL('notes').query('delete').where(['id', '=', noteId]).limit(1).exec()
res.status(204).send(null)
}
const handler = (req, res) => {
switch (req.method) {
case 'POST':
return saveNote(req, res)
case 'GET':
return listNotes(req, res)
case 'PUT':
return updateNote(req, res)
case 'DELETE':
return removeNote(req, res)
default:
return res.status(404).json({
statusCode: 404,
message: 'Not Found',
})
}
}
export default connectMiddleware(handler)
import { useDispatch } from 'react-redux'
import Clock from '../components/clock'
import Counter from '../components/counter'
import { tick } from '../lib/slices/clockSlice'
import useInterval from '../lib/useInterval'
const IndexPage = () => {
const dispatch = useDispatch()
// Tick the time every second
useInterval(() => {
dispatch(tick({ light: true, lastUpdate: Date.now() }))
}, 1000)
return (
<>
<Clock />
<Counter />
</>
)
}
export default IndexPage
import Dynamic from 'next/dynamic'
import Head from 'next/head'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import AddNoteForm from '../components/add-note'
import { deleteNote, loadNotes, selectNotes } from '../lib/slices/notesSlice'
import { PersistedNote } from '../types/Note'
const EditNoteForm = Dynamic(import('../components/edit-note'), { ssr: false })
const Notes = () => {
const [selectedNote, setSelectedNote] = useState<PersistedNote>()
const dispatch = useDispatch()
const { notes } = useSelector(selectNotes)
useEffect(() => {
async function dispatchLoadNotes() {
await dispatch(loadNotes())
}
dispatchLoadNotes()
}, [dispatch])
const renderNote = (note: PersistedNote) => (
<li key={note.id}>
<strong>{note.title}</strong>
<br />
<span>{note.content}</span>
<br />
<button
aria-label={`Delete note with title: ${note.title}`}
onClick={() => dispatch(deleteNote(note.id))}
>
🗑️
</button>
<button
onClick={() => setSelectedNote(note)}
aria-label={`Edit note with title: ${note.title}`}
>
✏️
</button>
</li>
)
return (
<>
<Head>
<title>Next.js with Redux Toolkit | Notes App</title>
</Head>
<AddNoteForm />
<hr />
<h3>All Notes</h3>
<ul>{notes.map(renderNote)}</ul>
{selectedNote && <EditNoteForm note={selectedNote} />}
</>
)
}
export default Notes
import { combineReducers, configureStore } from '@reduxjs/toolkit'
import clockReducer from '../lib/slices/clockSlice'
import counterReducer from '../lib/slices/counterSlice'
import notesReducer from '../lib/slices/notesSlice'
const rootReducer = combineReducers({
counter: counterReducer,
clock: clockReducer,
notes: notesReducer,
})
export type CoreState = ReturnType<typeof rootReducer>
export default configureStore({
reducer: rootReducer,
devTools: true,
})
{
"compilerOptions": {
"rootDirs": ["src/", "types/", "pages/", "lib/", "components/"],
"allowJs": true,
"alwaysStrict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "preserve",
"lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"target": "esnext"
},
"exclude": ["node_modules"],
"include": ["**/*.ts", "**/*.tsx"]
}
export type ErrorResponse = {
title: string
content: string
}
export function isErrorResponse(
error: ErrorResponse | string | undefined
): error is ErrorResponse {
return (error as ErrorResponse)?.title !== undefined
}
export type Note = {
title: string
content: string
}
export type PersistedNote = Note & {
id: string
}
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