0

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

3 Answers 3

2

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) => {
Sign up to request clarification or add additional context in comments.

1 Comment

thank u, this solved the problem .. I think it is being undefined for a bit only
2

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

1 Comment

I fixed , not like that
0

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>
          );
})

1 Comment

project is an object, not array

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.