Unverified Commit d16fb63c authored by Jaime Leonardo Suncin Cruz's avatar Jaime Leonardo Suncin Cruz Committed by GitHub

Improve Redux Toolkit example (#12858)

parent d0d59782
# Redux Toolkit example # Redux Toolkit example
This example shows how to integrate Redux with Toolkit in Next.js. This example shows how to integrate Next.js with [Redux Toolkit](https://redux-toolkit.js.org).
Redux toolkit makes it easier to configure a redux store, create reducers or dispatch actions, along with some default middlewares. This example demonstrates each of these tasks with Next.js 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 your own
......
import { useDispatch, useSelector } from 'react-redux'
import { addNote, selectNotes } from '../lib/slices/notesSlice'
import useForm from '../lib/useForm'
const AddNoteForm = () => {
const dispatch = useDispatch()
const { error } = useSelector(selectNotes)
const handleSubmit = useForm({
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 />
{'title' in (error || {}) && <small>{error.title}</small>}
<br />
<label htmlFor="contentText">
Content:
<textarea name="content" id="contentText"></textarea>
</label>
<br />
{'content' in (error || {}) && <small>{error.content}</small>}
<br />
<button type="submit">Add note</button>
<br />
{typeof error === 'string' && <small>{error}</small>}
</form>
)
}
export default AddNoteForm
import { useSelector, shallowEqual } from 'react-redux' import { useSelector } from 'react-redux'
const useClock = () => { import { selectClock } from '../lib/slices/clockSlice'
return useSelector((state) => {
return {
lastUpdate: state.lastUpdate,
light: state.light,
}
}, shallowEqual)
}
const formatTime = (time) => { const formatTime = (time) => {
// cut off except hh:mm:ss // cut off except hh:mm:ss
...@@ -15,7 +8,8 @@ const formatTime = (time) => { ...@@ -15,7 +8,8 @@ const formatTime = (time) => {
} }
const Clock = () => { const Clock = () => {
const { lastUpdate, light } = useClock() const { lastUpdate, light } = useSelector(selectClock)
return ( return (
<div className={light ? 'light' : ''}> <div className={light ? 'light' : ''}>
{formatTime(lastUpdate)} {formatTime(lastUpdate)}
......
import { createAction } from '@reduxjs/toolkit' import { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
const useCounter = () => { import {
const count = useSelector((state) => state.count) decrement,
increment,
incrementAsync,
incrementByAmount,
reset,
selectCount,
} from '../lib/slices/counterSlice'
const Counter = () => {
const dispatch = useDispatch() const dispatch = useDispatch()
const increment = () => dispatch(createAction('INCREMENT')()) const count = useSelector(selectCount)
const decrement = () => dispatch(createAction('DECREMENT')()) const [incrementAmount, setIncrementAmount] = useState('2')
const reset = () => dispatch(createAction('RESET')())
return { count, increment, decrement, reset } function dispatchIncrement() {
} dispatch(increment())
}
function dispatchDecrement() {
dispatch(decrement())
}
function dispatchReset() {
dispatch(reset())
}
function changeIncrementAmount(event) {
setIncrementAmount(event.target.value)
}
function dispatchIncrementByAmount() {
dispatch(incrementByAmount(Number(incrementAmount) || 0))
}
function dispatchIncrementAsync() {
dispatch(incrementAsync(Number(incrementAmount) || 0))
}
const Counter = () => {
const { count, increment, decrement, reset } = useCounter()
return ( return (
<div> <>
<h1> <div className="row">
Count: <span>{count}</span> <button
</h1> className="button"
<button onClick={increment}>+1</button> aria-label="Increment value"
<button onClick={decrement}>-1</button> onClick={dispatchIncrement}
<button onClick={reset}>Reset</button> >
</div> +
</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>
</>
) )
} }
......
import { useLayoutEffect, useRef } from 'react'
import { useDispatch } from 'react-redux'
import { editNote } from '../lib/slices/notesSlice'
import useForm from '../lib/useForm'
const EditNoteForm = ({ note = {} }) => {
const dialogRef = useRef()
const dispatch = useDispatch()
const handleSubmit = useForm(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}
></textarea>
</label>
<br />
<button type="submit">Edit</button>
<br />
</form>
</dialog>
)
}
export default EditNoteForm
import { createSlice } from '@reduxjs/toolkit'
const clockSlice = createSlice({
name: 'clock',
initialState: {
lastUpdate: 0,
light: true,
},
reducers: {
tick: (state, action) => {
state.lastUpdate = action.payload.lastUpdate
state.light = !!action.payload.light
},
},
})
export const selectClock = (state) => state.clock
export const { tick } = clockSlice.actions
export default clockSlice.reducer
import { createSlice } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
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) => 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) => (dispatch) => {
setTimeout(() => {
dispatch(incrementByAmount(amount))
}, 1000)
}
export default counterSlice.reducer
import { createAsyncThunk, createSelector, createSlice } from '@reduxjs/toolkit'
export const addNote = createAsyncThunk(
'notes/addNote',
async (newNote, 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(
'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(
'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(
'notes/deleteNote',
async (id, thunkAPI) => {
try {
await fetch(`/api/notes?noteId=${id}`, { method: 'DELETE' })
return id
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message })
}
}
)
const notesSlice = createSlice({
name: 'notes',
initialState: {
notes: [],
loading: 'idle',
},
reducers: {},
extraReducers: {
[addNote.pending]: (state) => {
delete state.error
},
[addNote.fulfilled]: (state, action) => {
state.notes.push(action.payload)
},
[addNote.rejected]: (state, action) => {
state.error = action.payload.error
},
[loadNotes.pending]: (state) => {
state.notes = []
state.loading = 'loading'
},
[loadNotes.fulfilled]: (state, action) => {
state.notes = action.payload
state.loading = 'loaded'
},
[loadNotes.rejected]: (state, action) => {
state.loading = 'error'
state.error = action.payload.error
},
[editNote.pending]: (state, action) => {
const note = state.notes.find((note) => note.id === action.meta.arg.id)
state.tempNote = Object.assign({}, note)
note.title = action.meta.arg.title || note.title
note.content = action.meta.arg.content || note.content
},
[editNote.fulfilled]: (state, action) => {
const note = state.notes.find((note) => note.id === action.payload.id)
delete state.tempNote
Object.assign(note, action.payload)
},
[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
},
[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)
},
[deleteNote.fulfilled]: (state) => {
delete state.backupNote
delete state.backupPosition
},
[deleteNote.rejected]: (state) => {
state.notes.splice(state.backupPosition, 0, state.backupNote)
delete state.backupPosition
delete state.backupNote
},
},
})
export const selectNotes = createSelector(
(state) => ({
notes: state.notes.notes,
error: state.notes.error,
}),
(state) => state
)
export default notesSlice.reducer
const useForm = (defaultValues = {}) => (handler) => async (event) => {
event.preventDefault()
event.persist()
const form = event.target
const data = Array.from(form.elements)
.filter((element) => element.hasAttribute('name'))
.reduce(
(object, element) => ({
...object,
[element.name]: element.value,
}),
defaultValues
)
await handler(data)
form.reset()
}
export default useForm
{ {
"name": "with-redux", "name": "with-redux-toolkit",
"version": "1.0.0", "version": "1.0.0",
"scripts": { "scripts": {
"dev": "next", "dev": "next",
...@@ -7,13 +7,12 @@ ...@@ -7,13 +7,12 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@reduxjs/toolkit": "^1.2.5", "@nano-sql/core": "^2.3.7",
"@reduxjs/toolkit": "^1.3.6",
"next": "latest", "next": "latest",
"react": "^16.9.0", "react": "^16.13.1",
"react-dom": "^16.9.0", "react-dom": "^16.13.1",
"react-redux": "^7.1.0", "react-redux": "^7.2.0"
"redux": "^3.6.0",
"redux-devtools-extension": "^2.13.2"
}, },
"license": "ISC" "license": "ISC"
} }
import { Provider } from 'react-redux' import { Provider } from 'react-redux'
import { store } from '../store'
import store from '../store'
const MyApp = ({ Component, pageProps }) => { const MyApp = ({ Component, pageProps }) => {
return ( return (
......
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 { createAction } from '@reduxjs/toolkit' import { useDispatch } from 'react-redux'
import { connect } from 'react-redux'
import useInterval from '../lib/useInterval'
import Clock from '../components/clock' import Clock from '../components/clock'
import Counter from '../components/counter' import Counter from '../components/counter'
import { tick } from '../lib/slices/clockSlice'
import useInterval from '../lib/useInterval'
const tick = createAction('TICK', (light) => { const IndexPage = () => {
return { const dispatch = useDispatch()
payload: {
light: light,
lastUpdate: Date.now(),
},
}
})
const IndexPage = ({ dispatch }) => {
// Use state or dispatch here
// Tick the time every second // Tick the time every second
useInterval(() => { useInterval(() => {
dispatch(tick(true)) dispatch(tick({ light: true, lastUpdate: Date.now() }))
}, 1000) }, 1000)
return ( return (
<> <>
<Clock /> <Clock />
...@@ -28,4 +20,4 @@ const IndexPage = ({ dispatch }) => { ...@@ -28,4 +20,4 @@ const IndexPage = ({ dispatch }) => {
) )
} }
export default connect((state) => state)(IndexPage) 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'
const EditNoteForm = Dynamic(import('../components/edit-note'), { ssr: false })
const Notes = () => {
const [selectedNote, setSelectedNote] = useState()
const dispatch = useDispatch()
const { notes } = useSelector(selectNotes)
useEffect(() => {
async function dispatchLoadNotes() {
await dispatch(loadNotes())
}
dispatchLoadNotes()
}, [dispatch])
const renderNote = (note) => (
<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>
<EditNoteForm note={selectedNote} />
</>
)
}
export default Notes
import { configureStore, createReducer } from '@reduxjs/toolkit' import { configureStore } from '@reduxjs/toolkit'
const initialState = { import clockReducer from './lib/slices/clockSlice'
light: false, import counterReducer from './lib/slices/counterSlice'
lastUpdate: 0, import notesReducer from './lib/slices/notesSlice'
count: 0,
}
const reducer = createReducer(initialState, { export default configureStore({
TICK: (state, action) => ({ reducer: {
...state, counter: counterReducer,
lastUpdate: action.payload.lastUpdate, clock: clockReducer,
light: !!action.light, notes: notesReducer,
}), },
INCREMENT: (state, action) => ({ ...state, count: state.count + 1 }), devTools: true,
DECREMENT: (state, action) => ({ ...state, count: state.count - 1 }),
RESET: (state, action) => ({ ...state, count: initialState.count }),
}) })
const initializeStore = (preloadedState = initialState) => {
return configureStore({
reducer,
preloadedState,
})
}
export const store = initializeStore()
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