Skip to content
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

22.01.15 Error Handling #164

Open
Seunghoya opened this issue Jan 16, 2022 · 0 comments
Open

22.01.15 Error Handling #164

Seunghoya opened this issue Jan 16, 2022 · 0 comments

Comments

@Seunghoya
Copy link
Collaborator

어떤 에러인가요?

  • setState 함수가 처리되는 과정에서 비동기로 처리되다보니 의도대로 상태가 변경되지 않아 상태를 활용할 수 없는 에러가 발생함.
  • setState 함수 자체가 비동기함수라 class 문법에서 콜백함수를 두 번째 인자로 불러서 활용하는 방법이 있었는데 해당 방법은 함수형 컴포넌트에선 적용이 안되는 문제가 있었음.
const getFolowFeedLists = useCallback(async () => {
    setLoading(true) // getFolowFeedLists 함수 실행시 loading 상태가 true로 바뀜
    await Axios.get(`http://localhost:4000/article/${userInfo.id}?page=${page}`)
    .then((res) => {
      setFolowFeedLists(followFeedLists => [...followFeedLists, ...res.data.articleData])
    })
    setLoading(false) // 서버 요청이 끝나고 getFolowFeedLists 실행이 종료되기 전 loading 상태가 다시 false로 바뀜
  }, [page])

위 코드에서 함수 getFolowFeedLists가 실행되면 setLoading가 바로 실행되어 loading상태가 변경되는 것을 의도했지만, 실제 개발자 도구에서 확인한 결과는 상태변경이 일어나지 않았다.

에러 핸들링 방법

  • setState 함수를 동기처리 하는 방법에 대해 학습하던 중, setState(state => {state.props})형식으로 콜백함수를 인자로 넘겨서 처리하면 된다는 식의 해결법을 찾았으나 해당 내용은 클래스문법에서 적용되던 방법이었고, 결론은 useEffect를 사용해 랜더링 될 때마다 동기적으로 함수가 실행되게 처리하는 방법을 적용했다.
useEffect(() => {
    function getFollowFeedLists () {
      if (more) {
        setLoading(true);
        setTimeout(() => {
          Axios({
            method: 'get',
            url: `http://localhost:4000/article/${state.userInfo.id}?page=${page}`,
            withCredentials: true,
            headers: {
              'Contnet-Type': 'application/json'
            }
          })
            .then((res) => {
              console.log('3')
              if (res.data.articleData.length === 0) {
                console.log('마지막줄');
                setMore(false);
              }
              console.log('4')
              setFolowFeedLists(followFeedLists => [...followFeedLists, ...res.data.articleData]);
              setLoading(false);
            });
        }, 1000);
      }
    }
    console.log('5')
    getFollowFeedLists();
  }, [state.userInfo.id, page, more])

해당 함수는 state.userInfo.id page more가 바뀔때마다 랜더링 되면서 getFollowFeedLists함수를 실행하므로 동기적으로 setLoading을 적용해 loading 상태를 동기적으로 관리할 수 있게 된다.

에러 핸들링을 위해 참고한 레퍼런스 링크

링크
링크
링크

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
No open projects
BookDam Project
Awaiting triage
Development

No branches or pull requests

1 participant