728x90
반응형
프로그래밍을 할 때, 함수의 인자를 객체로 묶어 전달하는 것은 종종 사용되는 패턴입니다. 이 글에서는 객체 인자를 사용하는 함수 호출에 대해 설명하고, 코드 오류를 수정한 경험을 공유하겠습니다.
문제 상황
다음과 같이 submitPost
함수를 호출할 때, 각 값들을 객체로 묶어서 전달했습니다:
dispatch(submitPost({ boardId, title, content, file }));
submitPost
함수의 인자는 객체로 전달되기 때문에, 호출되는 쪽에서도 객체의 프로퍼티명을 동일하게 맞춰줘야 합니다. 이전 코드에서는 boardId
부분이 board_id
로 되어 있어, 단순히 인자 순서만 맞추면 된다고 생각했지만 작동되지 않았습니다.
원인 분석
객체 인자로 인자를 받을 때, 객체의 프로퍼티명이 정확히 일치해야 합니다. 아래 코드를 보면, boardId를 객체 인자로 받습니다:
export const submitPost = createAsyncThunk(
"posts/submit",
async ({ boardId, title, content, file }, { rejectWithValue }) => {
console.log(boardId);
try {
const response = await axios.post("http://localhost:4000/api/posts", {
board_id: boardId,
user_id: 1,
title,
content,
});
if (file) {
const formData = new FormData();
formData.append("files", file);
await axios.post(
`http://localhost:4000/api/posts/${response.data.id}/upload`,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
}
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
핵심 포인트
- 함수 인자를 객체로 전달할 때는, 객체의 프로퍼티명이 함수 내부에서 사용하는 이름과 정확히 일치해야 합니다.
- 이전 코드에서 boardId 대신 board_id를 사용하여 문제가 발생했습니다.
수정 방법
호출하는 쪽과 호출되는 쪽의 객체 프로퍼티명을 일치시키면 문제를 해결할 수 있습니다. 다음은 수정된 코드입니다:
호출 코드
dispatch(submitPost({ boardId, title, content, file }));
함수 정의 코드
export const submitPost = createAsyncThunk(
"posts/submit",
async ({ boardId, title, content, file }, { rejectWithValue }) => {
try {
const response = await axios.post("http://localhost:4000/api/posts", {
board_id: boardId, // 이 부분을 변경하지 않았습니다.
user_id: 1,
title,
content,
});
if (file) {
const formData = new FormData();
formData.append("files", file);
await axios.post(
`http://localhost:4000/api/posts/${response.data.id}/upload`,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
}
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
결론
함수 인자를 객체로 전달할 때는 객체의 프로퍼티명이 정확히 일치해야 함을 유념해야 합니다. 이번 글에서는 객체 인자를 사용하는 함수 호출과 관련된 오류를 수정한 과정을 설명했습니다. 객체 인자를 사용하는 것은 코드의 가독성을 높이고, 인자 순서를 신경 쓰지 않아도 되는 장점이 있습니다. 다만, 프로퍼티명이 일치하지 않을 경우 예상치 못한 오류가 발생할 수 있으므로 주의해야 합니다.
반응형
'Javascript & Typescript' 카테고리의 다른 글
enum을 사용하는 이유 (0) | 2024.05.31 |
---|---|
TypeScript 컴파일 타임과 런타임에서의 URL 파라미터 처리 (0) | 2024.05.26 |
TypeScript 컴파일 과정 및 NestJS 프로젝트 빌드 (0) | 2024.05.26 |
Redux란 (0) | 2024.04.01 |
Typescript의 알 수 없는 return type 오류 (0) | 2024.03.14 |