Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- @media
- 자바
- 코딩테스트
- 그럼에도불구하고
- react
- max-width
- 반응형 페이지
- cleancode
- coding
- JavaScript
- HTML
- java
- JS
- github
- frontend
- 그럼에도 불구하고
- 코드업
- 프론트엔드
- node
- redux
- TypeScript
- 자바문제풀이
- 변수
- react-router-dom
- webpack
- git
- node.js
- Servlet
- media query
- CSS
Archives
- Today
- Total
그럼에도 불구하고
[Redux with TS] @reduxjs/toolkit nanoid에 대하여 본문
오늘은 id를 자동으로 생성해 주는 @reduxjs/toolkit nanoid에 대해 알아보겠습니다.
🧑🏻💻 nanoid
import { nanoid } from "@reduxjs/toolkit";
nanoId는 @reduxjs/toolkit안에 내장되어 되어있는 기능으로 자동으로 id를 생성해 줍니다.
예를들어, TodoList에 새로운 Post를 게시할 때 PostList의 각각의 post에 고유한 key를 지정할 경우 유용하게 사용할 수 있습니다.
📌 AddPostForm.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import React, { ChangeEvent, useState } from "react"; import { useDispatch } from "react-redux"; import { nanoid } from "@reduxjs/toolkit"; import { postAdded } from "../features/posts/postsSlice"; export const AddPostForm = () => { const [title, setTitle] = useState(''); const [content, setContent] = useState(''); const dispatch = useDispatch(); const onTitleChanged = (e: ChangeEvent<HTMLInputElement>) => setTitle(e.target.value); const onContentChanged = (e: ChangeEvent<HTMLTextAreaElement>) => setContent(e.target.value); const onSavePostClicked = () => { if( title && content ) { dispatch( postAdded({ id: nanoid(), title, content }) ) } setTitle(''); setContent(''); } return ( <section> <h2>Add a New Post</h2> <form> <label htmlFor="postTitle">Post Title:</label> <input type="text" id="postTitle" name="postTitle" value={title} onChange={onTitleChanged} /> <label htmlFor="postContent">Content:</label> <textarea id="postContent" name="postContent" value={content} onChange={onContentChanged} /> <button type="button" onClick={onSavePostClicked}>Save Post</button> </form> </section> ) } | cs |
const onSavePostClicked = () => {
if( title && content ) {
dispatch(
postAdded({
id: nanoid(),
title,
content
})
)
}
setTitle('');
setContent('');
}
아래와 같이 자동으로 id가 생성되는 걸 볼 수 있습니다.
'React > Redux' 카테고리의 다른 글
[Redux with TS] 새로고침해도 redux store를 유지하는 법 (0) | 2023.07.25 |
---|---|
[Redux] createAsyncThunk란? (0) | 2023.07.25 |
[Redux with TS] connect 고차 함수와 useSelector, useDispatch (0) | 2023.07.13 |
[Redux] redux-thunk와 redux-saga란? (1) | 2023.06.08 |
[Redux] Redux-logger 사용하기 (0) | 2023.06.08 |
Comments