0

I'm fairly new to react/redux and I have an unexpected issue that I can't understand

I retrieve a specific article from redux, the action is fired when I load the correct page. I can see in redux dev tools that the article is correctly loaded in state.article everything is working fine.

Reducer (simplified) :

const initialState = {
  article: null,
  loading: true,
};

export default function(state = initialState, action) {
  const { type, payload } = action;

  switch (type) {
    case GET_TARGET_ARTICLE:
      return {
        ...state,
        article: payload,
        loading: false
      };

}

Action :

export const getTargetArticle = slug => async dispatch => {
  try {
    const res = await axios.get("api/article/" + slug);
    dispatch({
      type: GET_TARGET_ARTICLE,
      payload: res.data
    });
  } catch (err) {
    ...
  }
};

Here is what the article object is supposed to have :

article: {
   title:"",
   content: "",
   comments:[],
}



Issue : As I said, state.article is correctly populated and I can access title and content. But when I try to access the comments, I get a nasty Cannot read property 'comments' of null. Any idea why ?

Here is how I display it if it helps :

const Article = ({ getTargetArticle, article: { article, loading }, match }) => {
  useEffect(() => {
    getTargetArticle(match.params.slug);
  }, []);

  let commentsList = article.comments.map((comment, index) => (
    <Fragment>{comment.title}</Fragment>
  ));

  return (
    <Fragment>
      {article && article.title}
      {commentsList}
    </Fragment>
  );
};

Thank you very much

1 Answer 1

1

At initial render comments will only have empty array so you can't iterator through it and there will be no title inside comments. So, comment.title is causing you the issue. To resolve this, check it before using map:

  let commentsList = article.comments.length && 
    article.comments.map((comment, index) => (
    <Fragment>{comment.title}</Fragment>
  ));

You may also check for title:

<Fragment>{comment.title && comment.title || ''}</Fragment>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it was it! (just had to check if article exists instead of article.comments.length though)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.