Skip to content

Commit

Permalink
Initial commit from Create Next App
Browse files Browse the repository at this point in the history
  • Loading branch information
tujlaky committed Mar 26, 2022
0 parents commit ed618a5
Show file tree
Hide file tree
Showing 23 changed files with 3,824 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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 README.md
Original file line number Diff line number Diff line change
@@ -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 a standardized 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&project-name=with-redux&repository-name=with-redux)

## 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 with-redux-app
# or
yarn create next-app --example with-redux with-redux-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)).
17 changes: 17 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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
5 changes: 5 additions & 0 deletions next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
32 changes: 32 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"type-check": "tsc",
"test": "jest"
},
"dependencies": {
"@reduxjs/toolkit": "^1.3.6",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.0.0",
"@testing-library/react": "^12.1.0",
"@testing-library/user-event": "^13.0.0",
"@types/jest": "^27.0.1",
"@types/node": "^16.9.1",
"@types/react": "^17.0.21",
"@types/react-dom": "^17.0.9",
"@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"
}
}
Binary file added public/favicon.ico
Binary file not shown.
1 change: 1 addition & 0 deletions public/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions setupTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import '@testing-library/jest-dom'
import { loadEnvConfig } from '@next/env'

loadEnvConfig(__dirname, true, { info: () => null, error: console.error })
48 changes: 48 additions & 0 deletions src/app/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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
24 changes: 24 additions & 0 deletions src/app/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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
79 changes: 79 additions & 0 deletions src/features/counter/Counter.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
.row {
display: flex;
align-items: center;
justify-content: center;
}

.row > button {
margin-left: 4px;
margin-right: 8px;
}

.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: 4px;
}

.button:hover,
.button:focus {
border: 2px solid rgba(112, 76, 182, 0.4);
}

.button:active {
background-color: rgba(112, 76, 182, 0.2);
}

.asyncButton {
composes: button;
position: relative;
}

.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;
}
105 changes: 105 additions & 0 deletions src/features/counter/Counter.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
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 '../../app/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()
})
})
Loading

0 comments on commit ed618a5

Please sign in to comment.