Redux News Reader: Unable to comment

I am stuck in the Redux News Reader project. I can’t post comments to the articles and no comments are appearing.

//CommentsSlice.js
// Import createAsyncThunk and createSlice here.
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
// Create loadCommentsForArticleId here.
export const loadCommentsForArticleId = createAsyncThunk(
  "comments/loadCommentsForArticleId",
  async (id) => {
    const response = await fetch(`api/articles/${id}/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: {
    // Add initial state properties here.
    byArticleId: {},
    isLoadingComments: false,
    failedToLoadComments: false,
    createCommentIsPending: false,
    failedToCreateComment: false,
  },
  // Add extraReducers here.
  extraReducers: {
    [loadCommentsForArticleId.pending]: (state, action) => {
      (state.isLoadingComments = true), (state.failedToLoadComments = false);
    },
    [loadCommentsForArticleId.fulfilled]: (state, action) => {
      state.byArticleId[action.payload.articleId] = action.payload.comments;
      (state.isLoadingComments = false), (state.failedToLoadComments = false);
    },
    [loadCommentsForArticleId.rejected]: (state, action) => {
      (state.isLoadingComments = false), (state.failedToLoadComments = true);
    },
    [postCommentForArticleId.pending]: (state, action) => {
      (state.createCommentIsPending = true),
        (state.failedToCreateComment = false);
    },
    [postCommentForArticleId.fulfilled]: (state, action) => {
      state.byArticleId[action.payload.articleId] = action.payload.comments;
      (state.createCommentIsPending = false),
        (state.failedToCreateComment = false);
    },
    [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;

//Comments.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  loadCommentsForArticleId,
  selectComments,
  isLoadingComments,
} from '../comments/commentsSlice';
import { selectCurrentArticle } from '../currentArticle/currentArticleSlice';
import CommentList from '../../components/CommentList';
import CommentForm from '../../components/CommentForm';

const Comments = () => {
  const dispatch = useDispatch();
  const article = useSelector(selectCurrentArticle);
  // Declare additional selected data here.
  const comments = useSelector(selectComments);
  const commentsAreLoading = useSelector(isLoadingComments);

  // Dispatch loadCommentsForArticleId with useEffect here.
useEffect( () => {
    if(article)
    dispatch(loadCommentsForArticleId(article.id));
    },[article,dispatch]
  ) 
  
  if (commentsAreLoading) return <div>Loading Comments</div>;
  if (!article) return null;

  return (
    <div className='comments-container'>
      <h3 className='comments-title'>Comments</h3>
      <CommentList comments={[]} />
      <CommentForm articleId={article.id} />
    </div>
  );
};

export default Comments;

//CommentList.js
import React from 'react';
import Comment from './Comment';

export default function CommentList({ comments }) {
  if (!comments) {
    return null;
  }
  
  return (
    <ul className='comments-list'>
      {comments.map(comment => {
        <Comment comment={comment} />
      })}
    </ul>
  );
}

//CommentForm.js

It looks like there might be an issue in the CommentList.js component. The comments.map method is not returning the JSX element for each comment. Instead, it should be wrapped in parentheses or have an explicit return statement.

To fix the issue, try modifying CommentList.js to:

import React from 'react';
import Comment from './Comment';

export default function CommentList({ comments }) {
  if (!comments) {
    return null;
  }
  
  return (
    <ul className='comments-list'>
      {comments.map(comment => (
        <Comment key={comment.id} comment={comment} />
      ))}
    </ul>
  );
}

Note the addition of the key prop to the Comment component, which helps React efficiently update the component when the comments list changes.

this should fix your issue :slight_smile:

Thanks for your help! Unfortunately, I’m still having a problem with the code. :confused:

Realized I had not completed step 9 of the project.
Here is the part I changed in Comments.js:

const commentsForArticleId = article ? comments[article.id] : [];

  if (commentsAreLoading) return <div>Loading Comments</div>;
  if (!article) return null;

  return (
    <div className="comments-container">
      <h3 className="comments-title">Comments</h3>
      <CommentList comments={commentsForArticleId} />
      <CommentForm articleId={article.id} />
    </div>
  );
};

The comments appear now.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.