0

I'm working on a node js and react app. I'm trying to fetch the following dataset from my back-end:

    [{"name":"nameonehere#1"},{"name":"nameonehere#2"},
{"name":"nameonehere#3"},{"nameonehere#4"},...,{"name":"nameonehere#xxx"}]

Here is my app.js:

class App extends Component {
state = {
    data: null,
    loading: true,
    error: false
  };

    componentDidMount() {
    fetch('http://localhost:5000/getData')
      .then(res => {
        if (!res.ok) {
          throw res;
        }
        return res.json()
      }).then(data => {
        // setState triggers re-render
        this.setState({loading: false, data});
      }).catch(err => {
        console.error(err);
        this.setState({loading: false, error: true});
      });
  }

  render() {
    return (
      <div className="App">
...
            <div>
        {this.state.loading ? <p>Loading...</p>
          : this.state.error ? <p>Error during fetch!</p>
          : (
              <ul>
                this.state.data.map(data =>
                <div key={data.id}>data: {data.name}</div>)
              </ul>
            )}
            </div>
      </div>
    );
  }
}

and I have the following error 'data' is not defined

the error is line 80 which is this line of code:

<div key={data.id}>data: {data.name}</div>)

I tried a few things but nothing is working. I'm a bit lost between JS and JSX.

What is the issue?

5
  • It says state.datas (with an s). Also' at what line do you get the error? Commented Oct 2, 2019 at 17:11
  • I would say the same, although 'data' is not defined doesn't make sense then, but that could be a typo to SO offcourse. Commented Oct 2, 2019 at 17:13
  • This is not a typo. I've updated my question about the line code error. the type was in the question not in the real code :p Commented Oct 2, 2019 at 17:16
  • how data looks like when returned from your API? Commented Oct 2, 2019 at 17:20
  • when opening the localhost:5000/getData I have the data exactly as I shared them as the beginning of my question. Is this answering your question? Commented Oct 2, 2019 at 17:23

2 Answers 2

1

You forgot to open { } when doing the this.state.data.map

It's considering that as text and failling on the key which tries to get a data variable.

You should add the brackets like so:

<ul>
    {
        this.state.data.map(data => <div key={data.id}>data: {data.name}</div>)
    }
</ul>
Sign up to request clarification or add additional context in comments.

Comments

1

When you write an expression in JSX you wrap it in curly braces So you need to wrap your map inside it as so

{
 this.state.data.map(data =>
 <div key={data.id}>data: {data.name}</div>
}

Hope this helps

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.