Nancy Moore
Nancy Moore

Reputation: 2470

How to display counting for each post in Reactjs

The code below works fine and display post records successfully.

Now I need to display post counter for each post based on post id(pid) but I am having error

this.state.post.counter is undefined

Here is what I have added

 {this.state.post.counter.res.map((co, c) => (
<li key={c}>
{co.counting}
              </li>

))}

How do I display counting where counting pid matches the pid of the post records?

Here is the full code:

<!DOCTYPE html>
<html>
   <head>

   </head>
   <body>
<script src="build/react.min.js"></script>
<script src="build/react-dom.min.js"></script>
<script src="build/browser.min.js"></script>
<script src="build/jquery.min.js"></script>

<div id="app"></div>

<script type="text/babel">

class Application extends React.Component {

//function Application() {
  constructor(props) {
    super(props);
    this.state = {

post: {"results": 
[
{"desc": "my first post", "pid": "101"},
{"desc": "my second post", "pid": "102"},
{"desc": "my 3rd post", "pid": "103"},

]},

counter: {"res": 
[
{"counting": "1000", "pid": "101"},
{"counting": "5600", "pid": "102"},
{"counting": "340", "pid": "103"},

]}


    };

  }




  render() {
    return (
      <div>
        <div>
          <ul>
            {this.state.post.results.map((obj, i) => (
              <li key={i}>
                {obj.pid} - {obj.desc}

               
 {this.state.post.counter.res.map((co, c) => (
<li key={c}>
{co.counting}
              </li>

))}

              </li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Application />, document.getElementById('app'));
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


   </body>
</html>

Upvotes: 1

Views: 867

Answers (1)

itsanewabstract
itsanewabstract

Reputation: 1036

Looks like you are trying to access this.state.post.counter.res which doesn't exist. You're looking for this.state.counter.res instead.

Change this.state.post.counter.res.map((co, c) => ... to this.state.counter.res.map((co, c) => ...

Here's a Codesandbox with a working example of your app.

EDIT

In order to render the correct counting value that's associated to each post by the pid property, you can write the following function:

getCounterByPid = pid => {
    const resIndex = this.state.counter.res.findIndex(el => pid === el.pid);
    return this.state.counter.res[resIndex].counting;
};

and then return it in your JSX as follows:

<ul>
   {this.state.post.results.map((obj, i) => (
      <li key={i}>
         {obj.pid} - {obj.desc}
         <span> Counting {this.getCounterByPid(obj.pid)}</span>
       </li>
    ))}
</ul>

Here's a Codesandbox containing the edited code.

Upvotes: 4

Related Questions