-
Notifications
You must be signed in to change notification settings - Fork 26
[황휘태] sprint7 #114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[황휘태] sprint7 #114
The head ref may contain hidden characters: "React-\uD669\uD718\uD0DC-sprint7"
Conversation
huuitae
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
질문 올렸습니다
| <Link | ||
| style={{ color: "black" }} | ||
| to={`/items/${product.id}`} | ||
| state={product} | ||
| key={product.id} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Product 컴포넌트로 상품을 보여주고 있습니다.
여기서 React Router의 Link를 통해 각 요소별로 링크를 만들어줍니다. ex) /items/119
저는 state로 이 상품의 정보를 전달해서 상품의 상세 정보를 보여주게끔 했습니다.
이전에 불러온 데이터를 사용함으로써 빠르게 보여주기 위해서 해당 방법을 사용한 것인데요
하지만 없는 데이터를 가져오기 위해서 상세페이지에서 결국 API 통신을 진행하게됩니다.
이 방법에 대해 어떻게 생각하시나요? 더 좋은 방법이 있을까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
와우.......... 질문 의도가 너무너무 좋습니다.
프로덕트 요구사항만 해결하실 것이 아니라 더 나은 방법도 탐구하시는군요.
말씀 주신대로 디테일 페이지와 리스트 페이지에서 필요한 데이터가 다르다면 현재 방법은 초기에 데이터를 일부 빠르게 보여줄 수 있으나 부정적인 사이드 이펙트(데이터가 일부 다르게 된다거나, 컨텐츠 길이가 갑자기 늘어나서 레이아웃 시프팅이 일어난다거나..)가 있을 수도 있겠네요.
또한 중요한 것은 데이터가 일부 있더라도 디테일 페이지만의 순수한 데이터를 API를 통해서 받아와야 합니다. 이 것을 해결할 수 있는 방법은 현재로서 논리적으로 불가능하지요. 없는 데이터를 만들어낼 수는 없으니까요.
질문의 요점은 그럼 이렇게 좁혀집니다.
사용자가 디테일 페이지를 빠르게 보여주는 방법이 없을까요?
물론 존재합니다 ! 지금 필요하신건 "프리페칭"으로 보이네요 !
말 그대로 "특정 타이밍"에 미리 데이터를 페칭하여 사용자가 다음 페이지로 이동할 때 처음 로딩 속도를 개선해주는 기법을 의미합니다. 😉
추 후 배우시게 될 NextJs에서는 다음과 같이 프리 페칭을 지원하고 있습니다 😊:
- Automatic prefetch
- Manual prefetch
- Hover-triggered prefetch
- Extending or ejecting link
- Disabled prefetch
그 외 프리페칭 방법은 다양하므로 한 번 이번 기회에 살펴보시는 것도 좋을 것 같네요 👍👍
|
스프리트 미션 하시느라 수고 많으셨어요. |
| /** | ||
| * 데이터 통신을 위한 공통 커스텀 훅 | ||
| * @param {Function} fetchFunction 서버와 직접 통신하는 함수 | ||
| * @returns {data: object, isLoading: boolean} | ||
| */ | ||
| const useService = (fetchFunction) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오오올... 이거 정말 멋진데요 ?? 👍
공통적으로 fetch에 대한 상태를 다루시고 계시네요 👍👍👍
주석도 꼼꼼하고.. fetchFunction 자체를 전달받도록 설계해두어 범용적으로 사용하기 좋아보이는 점도 인상깊어요 굿굿 ! 💯
| /** | ||
| * 데이터 통신을 위한 공통 커스텀 훅 | ||
| * @param {Function} fetchFunction 서버와 직접 통신하는 함수 | ||
| * @returns {data: object, isLoading: boolean} | ||
| */ | ||
| const useService = (fetchFunction) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(제안/선택) useService보다는 useFetch는 어떠신가요?
useService보다는 useFetch가 어떤 목적의 함수인지 명확히 알 수 있을 것 같아서 제안드려봅니다 ~!
| const getService = async (getDataFunction) => { | ||
| try { | ||
| setIsLoading(true); | ||
| const response = await getDataFunction(); | ||
|
|
||
| if (!response) { | ||
| throw new Error("서버와의 통신에 실패했습니다."); | ||
| } | ||
|
|
||
| setData(response); | ||
| } catch (error) { | ||
| setError(true); | ||
| console.error(error); | ||
| } finally { | ||
| setIsLoading(false); | ||
| } | ||
| }; | ||
|
|
||
| getService(fetchFunction); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(제안) get 말고 post, put, patch 등등 여러 메서드에도 사용될 수 있을 것 같은데요?
get 이라는 키워드는 없어도 될 것 같아요 😊
| const usePost = (postFetching) => { | ||
| const { data, isLoading, isError } = useService(() => postFetching); | ||
|
|
||
| return { data, isLoading, isError }; | ||
| }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오올.. useServic를 바로 사용하지 않는군요?
컴포넌트 단에서 useService를 바로 사용하는게 아니라 각 통신 별로 분리해두셨다는건 추 후 캐싱이나 옵션등 특정 도메인 커스텀 훅에 공통적으로 적용될 것을 고려하여(예외적인 상황을 고려해서) 이렇게 설계해두신 걸까요 ? 😏😏😏
어떤 의도인지는 모르겠으나 만들어두신 api 함수를 여기서 그냥 사용하셔도 될 것 같군요 !(따로 의도가 있다면 해당 제안은 무시하셔도 좋습니다 ~!)
| const usePost = (postFetching) => { | |
| const { data, isLoading, isError } = useService(() => postFetching); | |
| return { data, isLoading, isError }; | |
| }; | |
| const usePost = (data) => { | |
| const { data: response, isLoading, isError } = useService(() => requestPostInquiry(data)); | |
| return { data: response, isLoading, isError }; | |
| }; |
| <Link | ||
| style={{ color: "black" }} | ||
| to={`/items/${product.id}`} | ||
| state={product} | ||
| key={product.id} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
와우.......... 질문 의도가 너무너무 좋습니다.
프로덕트 요구사항만 해결하실 것이 아니라 더 나은 방법도 탐구하시는군요.
말씀 주신대로 디테일 페이지와 리스트 페이지에서 필요한 데이터가 다르다면 현재 방법은 초기에 데이터를 일부 빠르게 보여줄 수 있으나 부정적인 사이드 이펙트(데이터가 일부 다르게 된다거나, 컨텐츠 길이가 갑자기 늘어나서 레이아웃 시프팅이 일어난다거나..)가 있을 수도 있겠네요.
또한 중요한 것은 데이터가 일부 있더라도 디테일 페이지만의 순수한 데이터를 API를 통해서 받아와야 합니다. 이 것을 해결할 수 있는 방법은 현재로서 논리적으로 불가능하지요. 없는 데이터를 만들어낼 수는 없으니까요.
질문의 요점은 그럼 이렇게 좁혀집니다.
사용자가 디테일 페이지를 빠르게 보여주는 방법이 없을까요?
물론 존재합니다 ! 지금 필요하신건 "프리페칭"으로 보이네요 !
말 그대로 "특정 타이밍"에 미리 데이터를 페칭하여 사용자가 다음 페이지로 이동할 때 처음 로딩 속도를 개선해주는 기법을 의미합니다. 😉
추 후 배우시게 될 NextJs에서는 다음과 같이 프리 페칭을 지원하고 있습니다 😊:
- Automatic prefetch
- Manual prefetch
- Hover-triggered prefetch
- Extending or ejecting link
- Disabled prefetch
그 외 프리페칭 방법은 다양하므로 한 번 이번 기회에 살펴보시는 것도 좋을 것 같네요 👍👍
| const url = new URL( | ||
| `https://panda-market-api.vercel.app/products/${productId}/comments` | ||
| ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
baseURL을 지정 하시면 좋을 것 같군요 !
| const url = new URL( | |
| `https://panda-market-api.vercel.app/products/${productId}/comments` | |
| ); | |
| const BASE_URL = "https://panda-market-api.vercel.app" | |
| // ... | |
| const url = new URL( | |
| `${BASE_URL}/products/${productId}/comments` | |
| ); |
이렇게 하시면 중복되는 코드를 줄일 수 있으며 baseURL이 변경이 필요한 경우에도 효율적으로 운영할 수 있습니다 😉
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
또한 ! 추가로 base URL은 환경 변수에 저장하시는게 좋습니다!
환경 변수(Environment Variable): process.env에 내장되며 앱이 실행될 때 적용할 수 있는 값입니다!
다음과 같이 적용할 수 있습니다:
// .env.development
REACT_APP_BASE_URL="http://localhost:3000"
// .env.production
REACT_APP_BASE_URL="http://myapi.com"
// 사용시
<a href={`${process.env.REACT_APP_BASE_URL}/myroute`}>URL</a>
왜 환경 변수에 저장해야 하나요?
개발(dev), 테스트(test), 실제 사용(prod) 등 다양한 환경에서 앱을 운영하게 되는 경우, 각 환경에 따라 다른 base URL을 사용해야 할 수 있습니다. 만약 코드 내에 하드코딩되어 있다면, 각 환경에 맞춰 앱을 배포할 때마다 코드를 변경해야 하며, 이는 매우 번거로운 작업이 됩니다. 하지만, 환경 변수를 .env.production, .env.development, .env.test와 같이 설정해두었다면, 코드에서는 단지 다음과 같이 적용하기만 하면 됩니다.
const apiUrl = `${process.env.REACT_APP_BASE_URL}/api`;
이러한 방식으로 환경 변수를 사용하면, 배포 환경에 따라 쉽게 URL을 변경할 수 있으며, 코드의 가독성과 유지보수성도 개선됩니다.
실제 코드 응용과 관련해서는 다음 한글 아티클을 참고해보세요! => 보러가기
|
크으 ~ 휘태님 수고하셨습니다. 앞으로 어떻게 성장하실지 정말 기대가 되네요 🥺 수고하셨습니다 휘태님 ! |
요구사항
기본
심화
주요 변경사항
스크린샷
멘토에게