0

I have this quote.jsx file with a React component:

import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="quotes">
        {
          fetch('/random_quote')
            .then(res => res.json())
            .then(json => json.text())
        }
      </div>
    );
  }
}

As you may see, it uses fetch to get a JSON object with data related to a quote (quote text and author) and display some this data.

When I use webpack to bundle my system, I'm getting this warning message:

WARNING in ./fe/~/encoding/lib/iconv-loader.js 9:12-34 Critical dependency: the request of a dependency is an expression

And when I run my web system and visit the URL who should display this component, I got the following error:

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Quotes.

There is no error in my back-end and the JSON is being correctly generated and returned. This is not an issue.

I am relatively new to React.js and had never seen this message before.

Can someone help me with this? I've been fighting this error all my Sunday and have no more options to deal with it.

1
  • 1
    Perform the fetch inside componentDidMount then save the result into state, and in render access the state. Commented Jun 4, 2017 at 23:34

1 Answer 1

3

Don't perform the fetch inside render, instead do it in componentDidMount or componentWillMount.

Here is how I would implement it:

import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    fetch('/random_quote')
    .then(res => res.json())
    .then(json => {
      this.setState({text: json.text()});
    });
  }

  render() {
    return(
      <div className="quotes">
        {this.state.text}
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

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.