Simon Breton
Simon Breton

Reputation: 2876

Uncaught (in promise) ReferenceError: data is not defined in react component

I'm passing a simple JSON object from the back-end to the front-end {data: "test"}. I got the following error on the react side Uncaught (in promise) ReferenceError: data is not defined. I'm pretty sure I'm missing something obvious. Here is my Component:

export default class App extends Component {
  state = { data: null };

  componentDidMount() {
    fetch('/data',    {
          method: 'GET',
          withCredentials: true,
          headers: {
    'Content-Type': 'application/json', 
    'Access-Control-Allow-Origin': '*',
    'Accept': 'application/json' }})
      .then(res => res.json())
      .then(data => this.setState({ data }));
  }

  render() {
    const { data } = this.state;
    console.log(data)
    return (
      <div>
      <p> test </p>
      </div>
    );
  }
}

Upvotes: 1

Views: 2422

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

you try to set the state to data which does not exist, although the json is passed in as argument user.

You might want to use user

.then(user => this.setState({ data: user }));

or rename the argument to data

.then(data => this.setState({ data }));

Upvotes: 1

Related Questions