I'm very new to React JS, and I'm having trouble fully understanding where it is appropriate to fetch data from different locations. All of the documentation that I've found has stated that the componentDidMount() method is most appropriate for fetching data, although from what I see, it only is able to handle initial sync. In my application I need a more dynamic way of getting data. ex. A button is pressed, data is fetched and the dom changes. Putting my requests in the render method works, but all of the articles I've read frown upon the practice of loading data there.
-
Nevermind, just realized that I can utilize the componentDidUpdate() method! I feel so stupid now. Cheers.WillBDev– WillBDev2018-07-26 03:36:58 +00:00Commented Jul 26, 2018 at 3:36
3 Answers
You can create a function specifically for fetching data and call it inside componentDidMount() for the initial mounting of the component, and then attach the function as an event handler for onClick on the button. Store your response data from your fetch inside the component state. When someone clicks the button, the data will be re-fetched triggering a state update and subsequently a re-render.
Comments
You can look at the life cycle hook section. There are a lot more than just those two.
https://reactjs.org/docs/react-component.html
Keep in mind, some methods like componentWillMount are deprecated. I would keep away from those.