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

203
Vistas
El estado redux no tiene un valor actualizado en la función de devolución de llamada InterSectionObserver

Estoy usando IntersectionObserver api para implementar el desplazamiento infinito. Cuando se llama a la devolución de llamada, dentro de la callback de llamada, el estado redux no tiene un valor actualizado. Las funciones son:

 //function for defining InfiniteScroll const InfiniteScroll = (parent,target,options,callback,getObject)=>{ const Infoptions = { root: parent, rootMargin: '50px', threshold: 1.0, ...options } let observer = new IntersectionObserver(callback, Infoptions); observer.observe(target); getObject(observer); } export default InfiniteScroll;

Esta función se utiliza aquí:

 //calling InfiniteScroll const target = useRef(); const parent = useRef(); const observer = useRef(); const state = useSelector((state)=>state); useEffect(() => { if(!loading){ InfiniteScroll(parent.current, target.current, {}, callbackScroll, function (obs) { observer.current = obs; }) } return () => { observer.current&&observer.current.disconnect(); } }, [loading]) const callbackScroll = useCallback((data, observer) => { if (data[0].isIntersecting) { if ((state.post.data[postid]?.hasmorecomments) !== false){ //if there are more comments ,then this function will call api to fetch comments FetchPostComments(); //here (state.post.data[postid]) returns undefined value, //which is the initial value(when component has not mounted), //but in some_other function ,it returns updated value console.log((state.post.data[postid])); } } },[FetchPostComments])
 const some_other = ()=>{ //here it logs expected value(an object,not undefined) console.log(state.post.data[postid]); }

Quiero el valor actualizado dentro de la función callbackScroll como la función some_other . ¿Cómo puedo lograrlo?

Edit-1: código jsx donde se usa el objetivo

 //parent is the reference to scrollable div return ( <div ref={parent}> <Comments/> {//here too, state.post.data[postid] has updated value} {((state.post.data[postid]?.hasmorecomments) !== false)&&<Loader/>} <div ref={target}></div> </div> )
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

El propósito de utilizar useCallback es evitar la invocación innecesaria de funciones cada vez que se vuelve a representar un componente principal o uno mismo; esto se logra devolviendo una versión memorizada de la función de devolución de llamada, que se invoca solo cuando el estado o el valor de referencia en el cambio de matriz de dependencia. La función dentro de useCallback se ejecuta solo una vez cuando el componente se monta inicialmente con valores de estado iniciales. Por lo tanto, está devolviendo undefined . Le gustaría que se ejecutara nuevamente cuando se actualice el estado (es decir, invoque la función cuando se actualice el estado para que contenga más comentarios en este caso). Puede lograr esto simplemente incluyendo el estado en la matriz de dependencias de su useCallback .

 const callbackScroll = useCallback((data, observer) => { if (data[0].isIntersecting) { if ((state.post.data[postid]?.hasmorecomments) !== false){ //if there are more comments ,then this function will call api to fetch comments FetchPostComments(); //here (state.post.data[postid]) returns undefined value, //which is the initial value(when component has not mounted), //but in some_other function ,it returns updated value console.log((state.post.data[postid])); } } },[FetchPostComments,state]) //Include state in dependency array
about 4 years ago · Juan Pablo Isaza Denunciar

0

El problema era básicamente con la matriz de dependencias de useEffect y useCallback

 useEffect(() => { if(!loading){ InfiniteScroll(parent.current, target.current, {}, callbackScroll, function (obs) { observer.current = obs; }) } return () => { observer.current&&observer.current.disconnect(); } }, [loading,parent,target,callbackScroll,observer]) const callbackScroll = useCallback((data, observer) => { if (data[0].isIntersecting) { if ((state.post.data[postid]?.hasmorecomments) !== false){ //if there are more comments ,then this function will call api to fetch comments FetchPostComments(); //here (state.post.data[postid]) returns undefined value, //which is the initial value(when component has not mounted), //but in some_other function ,it returns updated value console.log((state.post.data[postid])); } } },[FetchPostComments,state]) //Include state in dependency array
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