강의

멘토링

커뮤니티

Inflearn Community Q&A

asfasfas's profile image
asfasfas

asked

Slack Clone Coding [Real-time Chat with React]

제로초님 swr 로 api 를 get 요청 할 떄

Written on

·

418

0

만약 tsx 파일에서 콘솔로그를 찍어보면? console.log(Product) 

https://api.minsu.com/product/${undefined} 이런 식으로 error 출력됩니다.

 왜 이러는 걸까요? 

 

id 값은 usePrams 로 

const { id } = useParams<{ id?: any }>() 으로 타입 지정 해 주었습니다.

 

api에 token 도 걸려 있어서 


    const token = 'minsu';
    // fetcher
    const fetchWithToken = (url: string, token: string) =>
    axios  
        .get(url, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        })
        .then(result => result.data);

 

이런 식으로 만들어 준 뒤. 

이런 식으로 코드 작성을 했는 데, {id} 값이 undefined 값 404 에러 나옵니다 ㅠㅠ

  const { data: ProductDetail } = useSWR(`https://api.minsu.com/product/${id}, url => fetchWithToken(url, token));
 
reacttypescriptSocket.iobabel웹팩클론코딩

Answer 2

1

zerocho님의 프로필 이미지
zerocho
Instructor

const fetchWithToken = <Data>(url...) => axios.get<Data>(...)

이렇게 두 군데 <Data> 추가해보세요.

zerocho님의 프로필 이미지
zerocho
Instructor

priceEnd로 변수명을 만드시면 되죠

minsu님의 프로필 이미지
minsu
Questioner

조현영님 Router 에는 문제가 없고, 

 useSWR<Product>(`https://api.minsu.com/product/${id}`)
이런식으로 하면 문제는 발생하지 않는데,
서버에 token 을 전달 해 주어야 해서.
 
 useSWR<Product>([`https://api.minsu.com/product/${id}`, token], fetchWithToken)
이런 식으로 하면
 
[string[], (url: string, token: string) => Promise<unknown>]' 형식의 인수는 'readonly [Key] | readonly [Key, Fetcher<Product> | null] | readonly [Key, Partial<PublicConfiguration<Product, any, Fetcher<Product>>> | undefined] | readonly [...]' 형식의 매개 변수에 할당될 수 없습니다.
'[string[], (url: string, token: string) => Promise<unknown>]' 형식은 'readonly [Key, Fetcher<Product> | null, Partial<PublicConfiguration<Product, any, Fetcher<Product>>> | undefined]' 형식에 할당할 수 없습니다.
소스에 2개 요소가 있지만, 대상에 3개가 필요합니다
 
이런 식으로 error 가 나오네요 그래서 <Date> 를 추가 해 볼려고 하는데 Date 가 라이브러리 모듈받아서 사용하는 건가요? 아니면 Date 스타일 컴포넌트를 만들어서 추가하라는 말씀이신가요!?
zerocho님의 프로필 이미지
zerocho
Instructor

아뇨 그냥 코드만 추가하시면 됩니다.

zerocho님의 프로필 이미지
zerocho
Instructor

Date가 아니라 Data입니다. Data가 아니고 D같은 아무거나 다 됩니다. 앞 뒤가 똑같기만하면 돼요

minsu님의 프로필 이미지
minsu
Questioner

minsu님의 프로필 이미지
minsu
Questioner

<Data> 를 추가 해 주니 주석 걸린 곳도 자동으로 풀리고 다른 부분들도 다 type error 가 뜨네요 

 


        const { data: ProductDetail } = useSWR([`https://api.minsu.com/product/${id}`], url => fetchWithToken(url, token))

으로 useSWR<Product> Product type 뺴고 시도 해 봤는데.

console.log(ProductDetail) 찍어 봤는데 

https://api.minsu.com/product/{undefined} 으로 나오네요. 

안되네요..

 

zerocho님의 프로필 이미지
zerocho
Instructor

강좌에서 코드를 변형하신거라서 어느 부분이 원인인지 감을 잡기 어렵습니다.

minsu님의 프로필 이미지
minsu
Questioner

감사합니다 제로초님 해결 됐습니다.

minsu님의 프로필 이미지
minsu
Questioner

제로초님 마지막으로 궁금 한게 있는데요ㅠㅠㅠ.. 

이것만 받고 조용히 사라지겠습니다.

왜 data 가 unknown 으로 지정 되는 지 모르겠습니다.

보통 slack 클론 했을 떈 useSWR<type> type 정의 안 해줘도 any 로 나왔는데,

왜 unknown 으로 나올까요...

zerocho님의 프로필 이미지
zerocho
Instructor

타입스크립트 버전이 업데이트 돼서 기본값이 any에서 unknown으로 바뀌었습니다. 더 타입이 엄격해진 겁니다.

minsu님의 프로필 이미지
minsu
Questioner

기존 월래 npm 에 설치 되어있던 typescript 4.4.4 버전에서 

제로초님 github slack typescript 버전 4.4.2 로 변경 했습니다. 

 

@react-dom, @react-router-dom 각각 제로초님 github slack 버전으로 설치 해도 unknown 으로 나오네요.  

tsconfig.json 에서 strict 을 false 로 바꿔도 map 함수를 사용 할 떄 unknown 은 출력 할 수 없다고 나옵니다. 

 

어디를 수정 해야 할까요.. 

zerocho님의 프로필 이미지
zerocho
Instructor

그러니까 unknown이 정상인 상태입니다. useSWR<Goods의타입>(...) 으로 쓰셔야 데이터 타이핑이 됩니다.

zerocho님의 프로필 이미지
zerocho
Instructor

제 강좌 소스코드도 전부 unknown이 나오게 업데이트 해둔 상황입니다.

0

zerocho님의 프로필 이미지
zerocho
Instructor

id는 <Route path="주소/:id" ...>에서 :id를 추출해서 나오는 겁니다.

아마 Route path가 주소/:id가 아니실겁니다.

minsu님의 프로필 이미지
minsu
Questioner

저는 product 에 있는 상품 목록들을 가져 올려고 했는데. 

https://api.minsu.com/product 이런 식으로 api get 요청을 받아야 하나요?

 

 

저는 slack 클론 강의 들으면서 

예로 들면 이런 식으로 멤버 API 를 ${workspace} 이런 식으로 workspace 에 해당 값들 member 를 가져왔어서  가져 오는 줄 알았습니다. 

  const { data: memberData } = useSWR<IUserWithOnline[]>(
    userData ? `/api/workspaces/${workspace}/members` : null,
    fetcher,
);
zerocho님의 프로필 이미지
zerocho
Instructor

주소가 http://.../product/1 처럼 아이디도 적으시고 Route path도 :id를 포함하게 만들어야 useParams의 id가 됩니다.

minsu님의 프로필 이미지
minsu
Questioner

 

App.tsx 에서 Router 만들어 준 뒤 에 <Route path="/product/:id/:brand/:gender component={<Product} />

 

main 컴포넌트 -> index.tsx 부분에서 

useParams 로 

   const {id,brand, gender } = useParams<{  id: any, brand: any, gender: string}>();

그리고 useSWR 로 불러 올려고 하고 있습니다.

 const { data: ProductDetail } = useSWR<ProductList>(`https://api.minsu.com/
product/${id}?brand=${brand}/gender=${gender}`, url => fetchWithToken(url, token), {
        dedupingInterval: 2000,
  });
 
const token = 'minsu';
    // fetcher
    const fetchWithToken = (url: string, token: string) =>
    axios  
        .get(url, {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        })
        .then(result => result.data);
 
console.log(ProductDetail)
 

Argument of type '[string, (url: any) => Promise<unknown>]' is not assignable to

parameter of type 'readonly [Key] | readonly [Key, Fetcher<ProductList[]> | null] |

readonly [Key, Partial<PublicConfiguration<ProductList[], any, Fetcher<ProductList[]>>> | undefined] | readonly [...]'.

  Type '[string, (url: any) => Promise<unknown>]' is not assignable to type 'readonly

[Key, Fetcher<ProductList[]> | null, Partial<PublicConfiguration<ProductList[], any,

Fetcher<ProductList[]>>> | undefined]'.

 

Source has 2 element(s) but target requires 3.

 

 

빨리 작업 시작 하고 싶은데 api 불러오는 쪽에서 error 가 나서 .. 힘드네요

(`https://api.minsu.app/product/${id}?age=${age}/gender=${gender}`, url => fetchWithToken(url, token), {
        dedupingInterval: 2000,
  });
 
여기 부분에 2가지 요소만 적혀 있어서 3가지 요소를 적어야 한다는 데, 나머지 한 요소를
무엇을 적어야 하는 지 모르겠습니다. ㅠㅠ

 

asfasfas's profile image
asfasfas

asked

Ask a question