Giter Club home page Giter Club logo

Comments (1)

bluepebble25 avatar bluepebble25 commented on June 12, 2024

겪은 문제

state의 비동기 업데이트로 인해 setState 이후에 바로 다시 setState하면 이전 데이터로 덮어씌워지는 현상

분명 데이터 fetchCards(page)를 해서 데이터를 불러온 다음 현재 페이지를 toggle해서 넘겨야 하는데 넘어가지 않았다.

페이지를 토글한 데이터를 setCardList하고 새 데이터를 fetch해와서 setCardList[...cardList, ...새 데이터] 처럼 기존 state를 스프레드해서 뒤집어 씌웠는데, state가 비동기 업데이트되어 이전 데이터가 덮어씌워진 것이다. 그래서 페이지 flip과 zIndex가 토글되지 않아 페이지가 넘어가지 않은 것이다.

그래서 거의 동시에 state에 접근해서 바로 setState가 반영이 안되는 문제를 해결하게 위해 callback을 쓰고 싶었는데 클래스형 말고 함수형 컴포넌트에서 쓰는 useState hook은 callback 함수를 인자로 받을 수 없었다. 그래서 useEffect로 처리하는 방법을 선택했다.

해결 방법

내가 원하는 동작은 다음 버튼을 눌러 location을 1 추가시켰을 때 만약 4의 배수번째 페이지라면 다음 데이터를 fetch해오는 것이다. 핵심은 'location이 변할 때'라는 것이기 때문에 초기 데이터 로드를 위한 useEffect 말고 또 새로운 useEffect를 만들고, dependencies 배열에는 location을 줬다. useEffect 안에는 만약 (4의 배수번째 location이고 마지막 페이지가 아니며, 뒤로가기 버튼을 눌렀다가 다시 다음 버튼을 눌러 이미 불려왔던 데이터가 없다면)이라는 조건을 주고 그 때만 fetch하도록 해서 location이 변할 때 무조건 fetch하지 않도록 했다.

(사실 처음에는 디펜던시 배열 안에 IDE에서 추천해주는 대로 자동완성을 눌러서 값을 집어넣었는데 무한로딩이 일어나서 진짜로 데이터를 fetch해오는 trigger인 location만 집어넣었다. 노란 밑줄이 신경쓰이기는 하지만 내가 원하는 동작의 trigger가 무엇인지 생각해서 진짜로 필요한 것만 집어넣도록 하자.)

from phoca-review.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.