Ahmad Ali
Ahmad Ali

Reputation: 774

Iterating over array inside object in JSX giving undefined

I am fetching data from my API :

  fetch('/api/p/' + project_id).then(res => res.json())
            .then((project) => {
                console.log(project)
                this.setState({ project })
            }
            );

the project structur is like this :

{
 name: "project1",
comments: ["com1", "com2"]
}

now inside my return function, I need to Loop through all comments and render them sparetly each comment on a different row so I used this code:

this.state.project.comments.map((comment) => {
           return (
               <p><i class="fas fa-chevron-right"></i> { comment } </p>
          );
 });

I am getting this Error:

TypeError: Cannot read property 'map' of undefined

I tried map or forEach and for. and also I can't get its length because I get the same error.

but if I type this.state.project.comments I get all elements in one row without space like this comment1comment2comment3

Upvotes: 0

Views: 162

Answers (3)

dmitrydwhite
dmitrydwhite

Reputation: 826

You're trying to .map on a value that's undefined. It's probably because this.state.project.comments isn't defined while you're fetching, but React is still trying to do the initial render.

Make sure you set an initial state somewhere, like

constructor() {
  super();

  this.state = { project: { comments: [] } };
}

Alternatively, you can give a default value right there when you call .map:

(this.state.project.comments || []).map((comment) => {

Upvotes: 2

Ankygurjar
Ankygurjar

Reputation: 115

What I can see from your code is that you are mapping the 'comments' but you are updating the project and that too you have to like

this.setState({
  project: res.data
})

and for mapping the data

this.state.project.map((project)=>{
   return (
               <p><i class="fas fa-chevron-right"></i> { project.comments } </p>
          );
})

Upvotes: 0

Tim Ackroyd
Tim Ackroyd

Reputation: 635

I think you're mapping over the wrong this, this line: this.state.comments.map((comment) => { should be this.state.project.comments.map((comment) => {

Upvotes: 2

Related Questions