프내기
[Promise]Property 'then' does not exist on type 'void' 본문
아까까지 잘 되던 애가 갑자기 왜이래..
ctrl + z를 쫙 돌려보니.
fetch함수를 쓰고있는 toDataURL 함수에 로직을 중괄호로 묶어주는 과정에서 난 에러였다.
해결
void 라는 키워드와 중괄호를 떠올려보니 함수의 반환 방식에 오류있어 발생된 에러가 아닐까 하는 추측을 했다.
화살표 함수(arrow function)에 대해서 조금 찾아보았다.
const arrowFn = () => (
<h1>Hello World</h1>
)
arrowFn() // <h1>Hello World</h1>
화살표 함수는 중괄호를 쓰지않고 ()로만 묶어줘도 return 처리를 한다.
하지만
중괄호를 쓰고 return 을 명시해주지 않는다면,
const arrowFn = () => {
<h1>Hello World</h1>
};
arrowFn() // undefiend
=> 리턴값 좀;;
undefined가 뜬다.
그러니 내 코드에서 문제는
"중괄호 썼는데 return 값도 없고 뭐하는거?" 에러이다.
원래는 복붙해온 코드에는 ()도 없었기 때문에 정리할 겸 중괄호로 묶어주었다가 봉변을 당한 것이다.
해결1
const toDataURL = (url: string) => (
fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
}))
)
해결2
async function toDataURL (url: string) {
return fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
}));
};
정리
// 1. 로직을 중괄호로 감싸주면 "return"을 써준다.
const add = (x, y) => {
return x + y;
]
// 2. 화살표 함수 내부에 return문 밖에 없는 경우에는 return문을 줄일 수 있다.
const add = (x, y) => x + y
// 3. 2번과 같지만 보기좋게 로직을 소괄호로 감싸줄 수 있다.
const add = (x, y) => (x + y)
// 4. 매개변수가 한 개라면 매개변수를 소괄호로 묶지 않을 수 있다.
const add = x => !x
'Trouble Shooting' 카테고리의 다른 글
[typescript] ~ is possibly 'undefiend' (0) | 2023.12.08 |
---|---|
[map / useState]파베에서 데이터 받아왔는데 배열에 업데이트가 안된다 (0) | 2023.11.30 |
[Firebase]이미지object 를 File 형식으로 변환하기 (1) | 2023.11.29 |
[Styled-component] Styled component에 props 넘기기(with TS) (2) | 2023.11.24 |
[styled-components]Global style, Theme 적용 오류 (2) | 2023.11.21 |