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?

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

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?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
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.

xadm
  • 8,219
  • 3
  • 14
  • 25