Skip to content
This repository has been archived by the owner on Jun 21, 2023. It is now read-only.

Commit

Permalink
feat: add exemple with redux toolkit in typescript (vercel#23250)
Browse files Browse the repository at this point in the history
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: vercel#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
  • Loading branch information
JulienKode committed Mar 22, 2021
1 parent de32f53 commit 7c0035b
Show file tree
Hide file tree
Showing 21 changed files with 976 additions and 0 deletions.
34 changes: 34 additions & 0 deletions examples/with-redux-toolkit-typescript/.gitignore
@@ -0,0 +1,34 @@
# 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
23 changes: 23 additions & 0 deletions examples/with-redux-toolkit-typescript/README.md
@@ -0,0 +1,23 @@
# 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)).
41 changes: 41 additions & 0 deletions examples/with-redux-toolkit-typescript/components/add-note.tsx
@@ -0,0 +1,41 @@
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
34 changes: 34 additions & 0 deletions examples/with-redux-toolkit-typescript/components/clock.tsx
@@ -0,0 +1,34 @@
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
156 changes: 156 additions & 0 deletions examples/with-redux-toolkit-typescript/components/counter.tsx
@@ -0,0 +1,156 @@
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
60 changes: 60 additions & 0 deletions examples/with-redux-toolkit-typescript/components/edit-note.tsx
@@ -0,0 +1,60 @@
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
29 changes: 29 additions & 0 deletions examples/with-redux-toolkit-typescript/lib/slices/clockSlice.ts
@@ -0,0 +1,29 @@
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

0 comments on commit 7c0035b

Please sign in to comment.