Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
Mutating state values in useEffect isn't working (react 16+, react-router v6)

I'm trying to fetch a url when the page first loads and when the location changes. The first load works fine. The record id is pulled from params and when that changes, useEffect gets called again to reset state and reload the new records. However, all of the set* calls in useEffect aren't doing anything as the loadData() method sees the old data still (hasMoreData=false, dataRecords=[...]).

export function MyComponent(props) {
  const [hasMoreData, setHasMoreData] = useState(true);
  const [dataRecords, setDataRecords] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const params = useParams();
  const location = useLocation();
  const { id } = params;

  const loadData = useCallback((page = 1) => {
    if (hasMoreData) {
      fetchSomeData(`api/records?id=${id}&page=${page}`).then((response) => {
        const { data } = response;
        // note: pagination logic omitted for clarity
        if (data && data.length > 0) {
          setDataRecords(data);
        } else {
          setHasMoreData(false);
        }
      });
    }
  }, [id, dataRecords, hasMoreData]);
  
  useEffect(() => {
    // id param has changed, or its the first load - reset all fields, then fetch new data
    setHasMoreData(true);
    setDataRecords([]);
    setCurrentPage(1);
    loadData(currentPage);
  }, [location]);

  // ...currentPage managed via infiniteScroll
};

What am I doing wrong here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Comments on the original question lead me to a better way to achieve what I was after. I needed to detect a location change, pagination changes and loading data on initial page load and useCallback wasn't the best way to go about this because the state changes are asynchronous and it didn't see the new values yet. Instead I used a separate useEffect() for changes to the location so I can reset the internal state data, and a second useEffect() to handle changes to currentPage rather than calling loadData() directly.

export function MyComponent(props) {
  const [hasMoreData, setHasMoreData] = useState(true);
  const [dataRecords, setDataRecords] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const params = useParams();
  const location = useLocation();
  const { id } = params;

  useEffect(() => {
    // location changed, reset all data
    setHasMoreData(true);
    setDataRecords([]);
    setCurrentPage(1);
  }, [location]);
  
  useEffect(() => {
    // id param has changed, or its the first load - reset all fields, then fetch new data
    loadData(currentPage);

    function loadData(page = 1) {
      if (hasMoreData) {
        fetchSomeData(`api/records?id=${id}&page=${page}`).then((response) => {
          const { data } = response;
          // note: pagination logic omitted for clarity
          if (data && data.length > 0) {
            setDataRecords(data);
          } else {
            setHasMoreData(false);
          }
        });
      }
    }
  }, [currentPage]);

  // ...currentPage managed via infiniteScroll
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda