Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda