0

Okay So I am sharing the code which is hard coded to 20 Emails only. I want to get list of emails untill it ends not just 20. So when I scroll I will be able to see nextPage. I know that gmail API has attribute called pagetoken but I am somehow not able to implement that.

I am using React-hooks to update the message. I am able to successfully see 20 Emails but I want to see them till end. Below is the front end of the code

   {isEmpty(messages) ? (
        <Box mt={6} display='flex' align='center' justifyContent='center'>
          <Spinner
            thickness='4px'
            speed='0.65s'
            emptyColor='gray.200'
            color='blue.500'
            size='xl'
          />
        </Box>
      ) : (
        <Box overflowY='auto'>
          {messages.map((message) => {
            const name = removeQuote(
              getHeader(message.payload.headers, "From").split("<")[0]
            );
            const subject = getHeader(message.payload.headers, "Subject");
            const msg = decodeHtml(message.snippet.substr(0, 75));
            const backgroundColor =
              message.labelIds.indexOf("UNREAD") > -1 ? "#fff" : "#E2E8F0";

            return (
              <Flex
                key={message.id}
                id={message.id}
                onClick={handleMessageClick}
                wrap='no-wrap'
                justify='space-around'
                py={2}
                bg={backgroundColor}
                borderTop='1px'
                borderBottom='1px'
                borderColor='gray.300'
                cursor='pointer'
              >
                <Avatar name={name} src='' />
                <Box w='80%'>
                  <Text fontSize='sm' color='gray.700' isTruncated>
                    {name}
                  </Text>
                  <Text
                    fontSize='md'
                    fontWeight='bold'
                    color='#3182ce'
                    isTruncated
                  >
                    {subject}
                  </Text>
                  <Text fontSize='xs' color='gray.500'>
                    {msg}
                  </Text>
                </Box>
              </Flex>
            );
          })}
        </Box>
      )}
    </Flex>
 const [message, setMessage] = useState({});
const getMessages = (labelIds = "INBOX") => {
    // Get List of 20 message's Id
    const request = window.gapi.client.gmail.users.messages.list({
      userId: "me",
      labelIds: labelIds,
      maxResults: 20,
    });

    setMessages([]);

    // Send Id list to getMessagesData to get Message Data foreach Id
    request.execute(getMessagesData);
  };

  const getMessagesData = (response) => {
    const messages = response.result.messages ? response.result.messages : [];

    messages.forEach((message) => {
      window.gapi.client.gmail.users.messages
        .get({
          userId: "me",
          id: message.id,
        })
        .then(
          (response) => {
           
            setMessages((messages) => [...messages, response.result]);
          },
          (err) => {
            console.error("getMessagesData error", err);
          }
        );
    });
  };

I should be able to load more Emails.

1 Answers1

1

According to the docs, the nextPageToken is included in the response.

https://developers.google.com/gmail/api/v1/reference/users/messages/list#response

You can do something like this:

let nextPageToken; // add me

const getMessages = (labelIds = "INBOX") => {
    // Get List of 20 message's Id
    const request = window.gapi.client.gmail.users.messages.list({
      userId: "me",
      labelIds: labelIds,
      maxResults: 20,
      pageToken: nextPageToken,  // changed
    });
...rest of function
};

const getMessagesData = (response) => {
  nextPageToken = response.nextPageToken;  // add me
  
  const messages = response.result.messages ? response.result.messages : [];
  
  messages.forEach((message) => {
...rest of function
}

From:

function listMessages(userId, query, callback) {
  var getPageOfMessages = function(request, result) {
    request.execute(function(resp) {
      result = result.concat(resp.messages);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.gmail.users.messages.list({
          'userId': userId,
          'pageToken': nextPageToken,
          'q': query
        });
        getPageOfMessages(request, result);
      } else {
        callback(result);
      }
    });
  };
  var initialRequest = gapi.client.gmail.users.messages.list({
    'userId': userId,
    'q': query
  });
  getPageOfMessages(initialRequest, []);
}
GitGitBoom
  • 1,512
  • 1
  • 5
  • Should work now, I had the wrong property on the request object. Changed to {pageToken: nextPageToken ...} – GitGitBoom Jul 09 '20 at 13:22
  • Hey I changed the code as you suggested but it is not loading new messages when I scrolldown to the end. – Dhruv patel Jul 09 '20 at 15:23
  • Even though I am able to get next page token, How would I be able to re request with this token. and what are changes that I have to do in frontend. Thank you for your help. – Dhruv patel Jul 09 '20 at 15:26
  • Every time you call your ```getMessages``` function you should be getting the next page, as long is it is called after the response has been received and the ```nextPageToken``` has been updated. On the first ```getMessages``` call it is undefined so you receive the first page but it will be defined for all subsequent calls with the token for the next page. – GitGitBoom Jul 09 '20 at 17:20
  • As for the 'infinite' part, your going to want to use a scroll event. This should help: https://stackoverflow.com/questions/5059526/infinite-scroll-jquery-plugin – GitGitBoom Jul 09 '20 at 17:23
  • Is there any meaning of From: section that you have mentioned. or it is just from official documentation. – Dhruv patel Jul 09 '20 at 17:35
  • Just part of the documentation that I pulled the handling of ```nextPageToken``` from. – GitGitBoom Jul 09 '20 at 17:47
  • Okay , I think you are right. it is loading nextpage token, now I need to do something in frontend. Like when i react end of the scrolling load function again. can you help me in it? – Dhruv patel Jul 09 '20 at 18:34
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/217556/discussion-between-dhruv-patel-and-gitgitboom). – Dhruv patel Jul 09 '20 at 18:36