짧기예 - 짧은 기능 구현 예제

0

짧은 기능 구현 예제 - 줄여서 짧기예

이 게시글에는 별도의 게시글로 닮기에는 너무 짧은 요소들을 나중에 빠르게 찾아보기 위해 정리하고자 한다.

⭐️ 프론트엔드

alert 이후 페이지 이동

alert 이후에는 react의 history가 작동하지 않았다.
https://stackoverflow.com/a/19825367

위의 해결책에 나온대로 이동하고자 하는 곳의 url을 window.location = '/some/url'로 강제로 윈도우를 이동시켜주는 방법이 있다.

추가 - useHistory 잘 작동한다.

window.history는 직접 DOM객체를 다루는 방식이다.

컨텐츠 크기에 따라 자동 height 조정

height : auto 

http://uxuiz.cafe24.com/wp/archives/1445

styled Component

override


import {  GoalWrapper } from './GoalElement';

export const GoalListWrapper = styled(GoalWrapper)`
  margin-left: 30px;
  padding: 10px;
  width: 100%;
`;

props 전달


//app
<GoalListWrapper
        key={goal._id}
        color={getColor(categoryList, goal.category)}
      >
         </GoalListWrapper>

//css
export const GoalListWrapper = styled(GoalWrapper)`
  margin-left: 30px;
  padding: 20px;
  width: 100%;
  background-color : ${(props)=> (props.color)}
`;

flex안 요소 하나 왼쪽 정렬, 오른쪽 정렬

왼쪽 정렬

margin-right: auto;

오른쪽 정렬

margin-left: auto;

https://nixpluvia.tistory.com/103

onClick 이벤트시 함수 자동 실행

react에서는 onClick 이벤트가 렌더링될 때 실행되고 클릭될때 실행이 되기 때문에 처음 onClick이벤트가 바인딩된 요소에 대해서 함수를 실행하는 것이 아닌 함수를 prop으로 주기만 해야 한다.

//잘못된 코드 
          <BsFillTrashFill
            style={style2}
            onClick={
              deleteGoal(goal._id, goal.contents);
            }
          />
        </Iconwrapper>
//수정 코드 
// 익명함수를 하나 추가로 정의해주었다. 

          <BsFillTrashFill
            style={style2}
            onClick={function () {
              deleteGoal(goal._id, goal.contents);
            }}
          />
        </Iconwrapper>

http://daplus.net/javascript-%EB%A0%8C%EB%8D%94%EB%A7%81%EC%8B%9C-%EB%B0%98%EC%9D%91-onclick-%ED%95%A8%EC%88%98-%EB%B0%9C%EC%83%9D/

⭐️ 백엔드

몽구스 쿼리

str -> ObjectId

import mongoose from 'mongoose';

const str = '6bacasfdj1241241'
const id = new Mongoose.Types.ObjectId(str)

https://stackoverflow.com/q/38446346

findById


  async findCategoryById(categoryId: string | Types.ObjectId) {
    const result = await this.categoryModel.findById({ _id: categoryId });
    if (!result) {
      throw new UnauthorizedException('해당하는 카테고리가 없습니다.');
    }

    return result;
  }

_id를 {}가 아닌 바로 string으로 넣을 경우(아무리 타입을 지정해주어도) 몽구스가 해당 string을 objectId로 인식하지 못해서 db에러가 나온다


//     잘못된 코드 
  async findCategoryById(categoryId: string | Types.ObjectId) {
    const result = await this.categoryModel.findById( categoryId );
    if (!result) {
      throw new UnauthorizedException('해당하는 카테고리가 없습니다.');
    }

    return result;
  }

결과값에서 특정 필드만 가져오기


result = await this.goalsModel.find().select('_id');

결과 값에서 _id 만 가져올 때
https://www.educative.io/edpresso/what-is-select-in-mongoose

not in + 특정 field 값 조건

  async getAllUsersGoals(goalExcluded: Array<Types.ObjectId>) {
    return await this.goalsModel.find({
      _id: { $nin: goalExcluded },
      softDelete: false,
    });
  }

⭐️ 기본언어

Array

Array -> set -> array

const arr = [1,1,1,2]
const set =  new Set(arr)
const setArr = [...set]

console.log(set.size); // 👉️ 4
console.log(set.has('c')); // 👉️ false
console.log(setArr) //👉️ [1,2]

https://bobbyhadz.com/blog/javascript-convert-array-to-set#:~:text=To%20convert%20an%20Array%20to%20a%20Set%20in%20JavaScript%2C%20pass,objects%2C%20that%20store%20unique%20values.

Array loop with index

const students = ["Mark", "Jane", "John", "Sarah"];

students.forEach((student, index) => {
    console.log(`The index for ${student} is ${index}`);
});

//'The index for Mark is 0'
//'The index for Jane is 1'
//'The index for John is 2'
//'The index for Sarah is 3'

string


const num = 11
const text = num.toString();

console.log(typeof text) 
//string

object 다루기

object keys & values


const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
console.log(Object.values(object1));
//expected output: Array  [ 'somestring', 42, false ]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

자동으로 가나다 순으로 정렬이 됌

https://dev.to/frehner/the-order-of-js-object-keys-458d

배열 다루기

javascript에서 마지막 요소에 접근하는 방법


const array = \[1,2,3\]

const lastElement = array\[array.length-1\]

가장 앞에 자료를 빼는법

집합

차집합


const goalsList = \[  
'a','b','c','d'  
\]

const completedGoal = \[  
'b','c'  
\]

const difference = goalsList.filter((x) => !completedGoal.includes(x));  
console.log(difference);

// ['a','d']

arr1에 각 요소들에 대해서 arr2에 포함되지 않는 요소만 필터링
es7부터 사용가능

https://stackoverflow.com/a/33034768

배열 - element 포함 여부 체크


const fruits = \["Banana", "Orange", "Apple", "Mango"\];  
fruits.includes("Mango");

include 메서드 사용

비었는지 확인

truty value -> true
falsy value -> false


const array = ''

!!array  
//false

const array2 = '11'

!!array2  
//true

map

map 기본 문법

const goalsList = goals.map((goal) => {
return goal._id;
});

return을 써주자 안그러면 undefined만 잔뜩 가득 찬 list를 얻게 된다.

https://www.digitalocean.com/community/tutorials/4-uses-of-javascripts-arraymap-you-should-know

map + 구조분해 할당


const goals = \[  
{id: 1, category: "12d212d1d", contents:"contnet1"},  
{id: 2, category: "12d212d1d", contents:"contnet2"},  
{id: 3, category: "12d212d1d", contents:"contnet3"}  
\]

const goalCtx = goals.map((goal)=>{  
const obj1 = {  
...goal,  
change:false }  
return obj1  
})

console.log(goalCtx)

/// 결과  
\[  
{  
id: 1,  
category: '12d212d1d',  
contents: 'contnet1',  
change: false  
},  
{  
id: 2,  
category: '12d212d1d',  
contents: 'contnet2',  
change: false  
},  
{  
id: 3,  
category: '12d212d1d',  
contents: 'contnet3',  
change: false  
}  
\]

moment js

last time of the yesterday


startDate: moment().subtract(1, 'day').endOf('day').format()  
//{ startDate: '2022-06-12T23:59:59+09:00' }

https://stackoverflow.com/questions/26930338/momentjs-how-to-get-last-day-of-previous-month-from-date

typescript

array of object 타입 표현


//표현하고자 하는 데이터 형태

\[  
{id : 1},  
{id ; 2},  
{id: 3}

\]

async InsertManyData(insertData: Array

) {  
return await this.scoreModel.insertMany(insertData);  
}

위와같이 object를 타입값으로 넣으면 아래 이미지와 같이 object를 타입으로 지정하지 말라는 경고가 나온다. 가장 잘 표현할 수 있는 방법은 무엇일까?


[##_Image|kage@v4dJE/btrCQvwCZ1Q/fDtUVljxqh81oXlCTmCu50/img.png|CDM|1.3|{"originWidth":1026,"originHeight":612,"style":"alignCenter"}_##]

⭐️ devOps

Git

git 되돌리기

git revert

https://www.lainyzine.com/ko/article/git-reset-and-git-revert-and-git-commit-amend/

Stash

stash 복구


git stash apply  
//가장 최근 stash 복구

\`\`\`

[https://gmlwjd9405.github.io/2018/05/18/git-stash.html](https://gmlwjd9405.github.io/2018/05/18/git-stash.html)
profile
기록을 통해 한 걸음씩 성장ing!

0개의 댓글