Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a slice for tracking comments data
- Loading branch information
1 parent
52bdf2a
commit 2ee7670
Showing
2 changed files
with
62 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import { createSlice, PayloadAction } from '@reduxjs/toolkit' | ||
|
||
import { Comment, getComments, Issue } from 'api/githubAPI' | ||
import { AppThunk } from 'app/store' | ||
|
||
interface CommentsState { | ||
commentsByIssue: Record<number, Comment[] | undefined> | ||
loading: boolean | ||
error: string | null | ||
} | ||
|
||
interface CommentLoaded { | ||
issueId: number | ||
comments: Comment[] | ||
} | ||
|
||
const initialState: CommentsState = { | ||
commentsByIssue: {}, | ||
loading: false, | ||
error: null | ||
} | ||
|
||
const comments = createSlice({ | ||
name: 'comments', | ||
initialState, | ||
reducers: { | ||
getCommentsStart(state) { | ||
state.loading = true | ||
state.error = null | ||
}, | ||
getCommentsSuccess(state, action: PayloadAction<CommentLoaded>) { | ||
const { comments, issueId } = action.payload | ||
state.commentsByIssue[issueId] = comments | ||
state.loading = false | ||
state.error = null | ||
}, | ||
getCommentsFailure(state, action: PayloadAction<string>) { | ||
state.loading = false | ||
state.error = action.payload | ||
} | ||
} | ||
}) | ||
|
||
export const { | ||
getCommentsStart, | ||
getCommentsSuccess, | ||
getCommentsFailure | ||
} = comments.actions | ||
export default comments.reducer | ||
|
||
export const fetchComments = (issue: Issue): AppThunk => async dispatch => { | ||
try { | ||
dispatch(getCommentsStart()) | ||
const comments = await getComments(issue.comments_url) | ||
dispatch(getCommentsSuccess({ issueId: issue.number, comments })) | ||
} catch (err) { | ||
dispatch(getCommentsFailure(err)) | ||
} | ||
} |