0
votes

I am trying to fetch inside a render function and have a then function that does something. My code is below. However, it doesn't seem to ever call the then function.

fetch(url, { method: "GET", headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': "*", "Cache-Control": "no-store" }, body: null }) .then(function (res) {console.log("here");finished++}) .catch(function (err) {console.log(err)});

while (finished<1) {}

I have tried adding a different number of parameters to the function being passed into the then function. I have also tried adding a finally block. comments show that the async call is successful and successfully returning, so I can't fathom what the problem is. Any help would be appreciated.

1

1 Answers

0
votes

You're not supposed to do asynchronous action inside the render method. Most of your get data API calls should be done inside the componentDidMount.

Your render method always should be more concerned about returning UI. Render methods should be pure, it's mean that it only uses state and props to render, never try to modify the state or do any other actions in render.

export default class App extends React.Component {
  constructor() {
    super();
    this.state = { data: null }
  }
  

  async componentDidMount() {
    const apiData = await fetch();
    const jsoned = await apiData.json();
    this.setState({ data: jsoned });
  } 

  render() {
    if (!data) return null;

    return (
      <div>
        {data.map()}
      </div>
    );
  }
}