Skip to content

Commit

Permalink
Step 15.7: Implement pagination with context and hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilkisiela authored and Urigo committed Jul 20, 2019
1 parent 265adac commit b21664b
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion src/components/ChatRoomScreen/index.tsx
@@ -1,6 +1,6 @@
import gql from 'graphql-tag';
import React from 'react';
import { useCallback } from 'react';
import { useCallback, useState, useContext, useEffect } from 'react';
import { Redirect } from 'react-router-dom';
import { useApolloClient } from 'react-apollo-hooks';
import styled from 'styled-components';
Expand Down Expand Up @@ -45,6 +45,48 @@ const addMessageMutation = gql`
${fragments.message}
`;

const PaginationContext = React.createContext({
after: 0,
limit: 20,
/**
* Sets new cursor
*/
setAfter: (after: number) => {},
/**
* Resets `after` value to its inital state (null) so
*/
reset: () => {},
});

const usePagination = () => {
const pagination = useContext(PaginationContext);

// Resets the pagination every time a component did unmount
useEffect(() => {
return () => {
pagination.reset();
};
}, [pagination]);

return pagination;
};

export const ChatPaginationProvider = ({ children }: { children: any }) => {
const [after, setAfter] = useState<number | null>(null);

return (
<PaginationContext.Provider
value={{
limit: 20,
after: after!,
setAfter,
reset: () => setAfter(null),
}}>
{children}
</PaginationContext.Provider>
);
};

export const useGetChatPrefetch = () => {
const client = useApolloClient();

Expand Down

0 comments on commit b21664b

Please sign in to comment.