그럼에도 불구하고

👨‍💻

[Redux with TS] @reduxjs/toolkit nanoid에 대하여 본문

React/Redux

[Redux with TS] @reduxjs/toolkit nanoid에 대하여

zenghyun 2023. 7. 21. 14:49

 

 

오늘은 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가 생성되는 걸 볼 수 있습니다.

Comments