Skip to content

Commit

Permalink
Add a slice for tracking comments data
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Nov 15, 2019
1 parent 52bdf2a commit 2ee7670
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/app/rootReducer.ts
Expand Up @@ -3,11 +3,13 @@ import { combineReducers } from '@reduxjs/toolkit'
import issuesDisplayReducer from 'features/issuesDisplay/issuesDisplaySlice'
import repoDetailsReducer from 'features/repoSearch/repoDetailsSlice'
import issuesReducer from 'features/issuesList/issuesSlice'
import commentsReducer from 'features/issueDetails/commentsSlice'

const rootReducer = combineReducers({
issuesDisplay: issuesDisplayReducer,
repoDetails: repoDetailsReducer,
issues: issuesReducer
issues: issuesReducer,
comments: commentsReducer
})

export type RootState = ReturnType<typeof rootReducer>
Expand Down
59 changes: 59 additions & 0 deletions src/features/issueDetails/commentsSlice.ts
@@ -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))
}
}

0 comments on commit 2ee7670

Please sign in to comment.