항해/TIL

TIL(3/7) / level5 과제 중 에러들

yeeendy 2024. 3. 7. 11:12

첫 번째

input에 minlength, maxlength, pattern이 안 먹혀서 따로 함수 구현해야함 => 추후 구현 예정


두 번째

useEffect에 async await 적용하기

useEffect(async () => {
const data = await fetchUser(userId);
setUser(data);
}, [userId]);

이런 식으로 하면 부수 효과 때문에 에러가 난다

 

에러 해결

useEffect(() => {
async function fetchAndSetUser() { 1
	const data = await fetchUser(userId);
	setUser(data);
   }
   fetchAndSetUser(); 2
},[userId]);

useEffect 내에서 async await 함수를 만들고 그 함수를 호출해서 사용해야 한다.

참조 https://velog.io/@he0_077/useEffect-%ED%9B%85%EC%97%90%EC%84%9C-async-await-%ED%95%A8%EC%88%98-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0


세 번째

// TodoDetail.jsx에서
const [posts, setPosts] = useState([]);

useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get("http://localhost:4000/posts");
        console.log(response);
        setPosts(response.data);
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, []);
  
console.log("posts", posts);

왜 이렇게 뜰까?! response.data 부분만 뽑아내고 싶은데!!! 첫 줄 때문에 빈 배열이 나오는 건 알겠지만 나는 데이터만 뽑아내고 싶다!

const foundData = posts.find((post) => post.id === params.id);
console.log("foundData", foundData); //undefined

posts를 제대로 받아와야 foundData를 가져오는데 위 코드 posts에서 에러가 나니 foundData는 당연히 undefined가 뜬다....

에러 해결

<Route path="/works/:idssss" element={<TodoDetail />} />

세상에 .... useParams()값 출력해보려고 :id를 :idssss 로 바꿔 테스트 해서 안 된 거였다.

오타를 조심하자........

'항해 > TIL' 카테고리의 다른 글

TIL(3/6) / aws s3 액세스 키 발급  (0) 2024.03.07
TIL(3/5) / react-query로 todolist 리팩토링  (0) 2024.03.05
TIL(3/2) / CSR, SSR  (0) 2024.03.02
TIL(2/29) / lv3  (0) 2024.02.29
TIL(2/28) / React Query  (0) 2024.02.28