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

303
Visualizações
React - Get paginated data from context

I have the current context

export function UserPostsProvider({ children }) {
  const [posts, dispatch] = useReducer(userPostsReducer, initialState);

  const addUserPosts = (userId, posts, unshift = false) => {
    dispatch(actionCreators.addUserPosts(userId, posts, unshift));
  };

  const getUserPosts = (userId, index = 0, limit = undefined) => {
    const _posts = posts[userId] ?? [];
    return _posts.slice(index, limit + index || undefined);
  };

  return (
    <UserPostsContext.Provider
      value={{
        addUserPosts,
        deleteUserPost,
        getUserPosts,
      }}
    >
      {children}
    </UserPostsContext.Provider>
  );
}

As you can see, I have a method "getUserPosts" which accepts two arguments "index" and "limit".

I am consuming this context as follows:

export default function useFetchUserPosts(userData) {
  const isMounted = useIsMounted();

  const userPosts = useUserPosts();

  const cards = useCards();

  const posts = userPosts.getUserPosts(userData.id); // <--- HERE!
  const [isLoading, setIsLoading] = useState(!posts.length);
  const [error, serError] = useState(undefined);

  const startAfter = useRef(new Date()); 

  const getMorePosts = async (limit = 10) => {
     if (isFetching.current || !hasMoreToLoad.current || !isMounted()) {
           return;
     }

     isFetching.current = true;

     setIsLoading(true);

     try {
        const {
           posts: newPosts,
           hasMoreToLoad: newHasMoreToLoad,
           startAfter: newStartAfter,
        } = await getUserPosts(userData.id, startAfter.current, limit);

        // The component might be unmounted
        if (!isMounted()) return;

        hasMoreToLoad.current = newHasMoreToLoad;

        startAfter.current = newStartAfter;

        userPosts.addUserPosts(userData.id, newPosts);

        setIsLoading(false);

        isFetching.current = false;
     } catch(err) {
       setError(err);
     }         
  }
  
  ...
}

How can I do to get the correct a paginated section of the posts from the context? I mean, if I just get the first 10 posts from the context on each re-render, I will be always getting the first 10 posts, no more than that.

Any helps?

about 4 years ago · Juan Pablo Isaza
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