반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

id를 랜덤하게 정해주는 shortId 본문

리액트

id를 랜덤하게 정해주는 shortId

5_hyun 2023. 1. 13. 20:55

shortId

-npm 주소

https://www.npmjs.com/package/shortid

 

shortid

Amazingly short non-sequential url-friendly unique id generator.. Latest version: 2.2.16, last published: 2 years ago. Start using shortid in your project by running `npm i shortid`. There are 4230 other projects in the npm registry using shortid.

www.npmjs.com

map에서 key를 주는 등 개발을 하다보면 각각 다른 값을 넣어줘야하는 경우가 있다. 각각 값을 넣어주기 애매한 경우에 shortId 라이브러리를 사용하면 값이 거의 중복되지 않게 만들어준다.

사용법

import shortId from "shortid";

//...

const dummyPost = (data) => ({
  id: shortId.generate(),
  content: data,
  User: {
    id: 1,
    nickname: "오리",
  },
  Images: [],
  Comments: [],
});

이런식으로 id 부분에 shortId.generate()를 해주면 랜덤한 값이 설정된다.

728x90
반응형
Comments