Everything works on this project except posting comments. I’ve been going through forums/solution code on github/chatGPT, etc and cannot figure out what the problem is. I know it is something in my commentsSlice.js file (code below) because if I copy and paste someone else’s code with builder instead of extraReducers it works perfectly. But the functionality should be the same so not sure why it’s not working the way I have it…
// Import createAsyncThunk and createSlice here.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
// Create loadCommentsForArticleId here.
export const loadCommentsForArticleId = createAsyncThunk('comments/loadCommentsForArticleId',
async (articleID) => {
const response = await fetch(`api/articles/${articleID}/comments`);
const json = await response.json();
return json;
})
// Create postCommentForArticleId here.
export const postCommentForArticleId = createAsyncThunk(
'comments/postCommentForArticleId',
async ({articleId, comment}) => {
const requestBody = JSON.stringify({comment: comment})
const response = await fetch(`api/articles/${articleID}/comments`, {
method: 'POST',
body: requestBody
});
const json = await response.json();
return json;
})
export const commentsSlice = createSlice({
name: 'comments',
initialState: {
byArticleId: {},
isLoadingComments: false,
failedToLoadComments: false,
createCommentIsPending: false,
failedToCreateComment: false
},
extraReducers: {
[loadCommentsForArticleId.pending]: (state, action) => {
state.isLoadingComments = true;
state.failedToLoadComments = false;
},
[loadCommentsForArticleId.fulfilled]: (state, action) => {
state.isLoadingComments = false;
state.failedToLoadComments = false;
const { articleId, comments} = action.payload;
state.byArticleId[articleId] = comments;
},
[loadCommentsForArticleId.rejected]: (state, action) => {
state.isLoadingComments = false;
state.failedToLoadComments = true;
state.byArticleId = {};
},
[postCommentForArticleId.pending]: (state, action) => {
state.createCommentIsPending = true;
state.failedToCreateComment = false;
},
[postCommentForArticleId.fulfilled]: (state, action) => {
state.createCommentIsPending = false;
state.failedToCreateComment = false;
state.byArticleId[action.payload.articleId].push(action.payload)
},
[postCommentForArticleId.rejected]: (state, action) => {
state.createCommentIsPending = false;
state.failedToCreateComment = true;
}
}
});
export const selectComments = (state) => state.comments.byArticleId;
export const isLoadingComments = (state) => state.comments.isLoadingComments;
export const createCommentIsPending = (state) => state.comments.createCommentIsPending;
export default commentsSlice.reducer;