2

When I check the length of item, and trying to add in to template, getting error. any one help me to fix this issue?

here is my code :

import React from "react";
import "./style-posts.css";
import { connect } from "react-redux";
import { setTitle, titleHandler } from "../actions/postActions";

const ShowPosts = props => {
  if (props.posts.length) {
    const postItems = props.posts.map(post => {
      <div key={post.id}>
        <h3>{post.title}</h3>
        <p>{post.body}</p>
      </div>;
    });
  }

  return (
    <div>
      {props.posts.length ? postItems : null} //postItems is not defined
      <button onClick={props.showPosts}>Show Posts On Click </button>
    </div>
  );
};

export default connect(
  setTitle,
  titleHandler
)(ShowPosts);

getting error as postItems is not defined - what is wrong with me code? any one figure out?

2 Answers 2

1

Its because postItems is a const and you defined postItems variable inside if block, so it will be available in that block only. (let and const have block scope and var has function level scope).

Write it like this:

let postItems = null;

if (props.posts.length) {
    postItems = props.posts.map(post => (
        <div key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.body}</p>
        </div>;
    ));
}

Or use var instead of const.

if (props.posts.length) {
    var postItems = props.posts.map(post => (
        <div key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.body}</p>
        </div>;
    ));
}

I will suggest to check this answer for difference between let, var and const:

What's the difference between using "let" and "var" to declare a variable in JavaScript?

Sign up to request clarification or add additional context in comments.

3 Comments

will it work with const I think let should be there
@Revansiddh my mistake, updated the answer thanks :)
because you are not returning anything from map callback method. check the updated answer.
0

It can be const:

const postItems = !props.posts.length ? []
  : props.posts.map(post => (
    <div key={post.id}>
      <h3>{post.title}</h3>
      <p>{post.body}</p>
    </div>;
  ));

No rendered data because no mapStateToProps, no proper mapDispatchToProps, simply bad redux connect usage.

Comments

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.