Met Den
Met Den

Reputation: 65

Nothing was returned from render at promise return

I need to make a request to API and only after render my page. For this, I used async function and in return method, I used to promise, but I get the error:

Nothing was returned from render.

class Main extends Component {
    constructor(props) {
       super(props)
       this.data = []
    }

    async getRequest() {
       const response = await fetch({'http://my url'})
       const data = await response.json();
       //exampe
       this.data = data[0]
       return respons
    }

    render() {
        this.getRequest()
            .then((data) => {
               return(
                  <div>
                    {this.data}
                  </div>
               )
            }
     }
}

I think the best, is use promise. How fixed? Thanks

Upvotes: 2

Views: 631

Answers (1)

Mrchief
Mrchief

Reputation: 76208

You cannot data fetches and promises in your render. You should move all the API calls to componentDidMount and render should be just returning the elements.

componentDidMount() {
    this.getRequest()
        .then((data) => { this.setState({ data }) })
}

render() {
    return(
        <div>
        {this.state.data}
        </div>
    )
}

As noted in comments, for SSR, you can try using getDerivedStateFromProps in place of componentDidMount. This will require React v16.3 and above.

Upvotes: 1

Related Questions