0

I have to make a request using axios in order to fetch some data which should be passed as a prop to a React Component. Following is my render function:

render() {
    boards = this.fetchBoardList();

return (
    <div className="app-wrapper">
        // Some HTML code
    </div>
);
}

fetchBoardList is an async function, so it will return a promise. I can attach then and catch handlers to the return promise but in that case, I would have to put the same HTML code in both of the handlers. Is there any other way to do this?

Rahul Gusai
  • 701
  • 1
  • 6
  • 11
  • This is not how react is intended to be used. Please take a look at typical error handling in react: https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html – Michael Hirschler Feb 12 '21 at 12:19
  • 1
    Put the fetching logic in componentDidMount, and set your state once your promise resolves. This will naturally cause your component to re-render, which can use the state that was set – Nick Parsons Feb 12 '21 at 12:19
  • @NickParsons But prior to the stage when fetching logic actually runs and fetched the data, the component would render with empty data set from the state. How to avoid that? – Rahul Gusai Feb 13 '21 at 18:17
  • @RahulGusai You cannot avoid it. The data is not there yet. – Bergi Feb 13 '21 at 19:12
  • @RahulGusai as Bergi pointed out you can't. Usually, you'll do a check to see if the state/data you want to use is defined, and if it is not, display a loading component of some sort, otherwise, it if is defined, display your regular component. – Nick Parsons Feb 14 '21 at 00:18

1 Answers1

1

There are multiple problems with that snippet of React code.

  • The boards variable shouldn't be global. You probably want to store the data in state using, for example, the useState hook.
  • I assume you want to fetch the data when the component mounts, and for that end you should use the useEffect hook (with a dependency on boards)
  • You are using class in your jsx, which is not valid. You should be using className.

The first two points apply to functional components only. If you want to use class components:

  • Create initial state in the constructor. Add a componentDidMount function where you await the fetch function call and call this.setState with the resulting data.
nip
  • 1,609
  • 10
  • 20