Last active
November 16, 2018 18:44
-
-
Save productioncoder/d8e236c1c30a8d5a40175e329aa572e1 to your computer and use it in GitHub Desktop.
Youtube in React: incorporating the commentThread response into our global state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reduceCommentThread(response, videoId, prevState) { | |
if (!response) { | |
return prevState; | |
} | |
const newComments = response.items.reduce((acc, item) => { | |
acc[item.id] = item; | |
return acc; | |
}, {}); | |
// if we have already fetched some comments for a particular video | |
// we just append the ids for the new comments | |
const prevCommentIds = prevState.byVideo[videoId] ? prevState.byVideo[videoId].ids : []; | |
const commentIds = [...prevCommentIds, ...Object.keys(newComments)]; | |
const byVideoComment = { | |
nextPageToken: response.nextPageToken, | |
ids: commentIds, | |
}; | |
return { | |
...prevState, | |
byId: { | |
...prevState.byId, | |
...newComments, | |
}, | |
byVideo: { | |
...prevState.byVideo, | |
[videoId]: byVideoComment, | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment