WillBDev
WillBDev

Reputation: 113

React JS Dynamic Data Fetching

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.

Upvotes: 0

Views: 3734

Answers (3)

Adnan
Adnan

Reputation: 1707

Just call a function on click of the button and call the api and in the success response of api setState() of the component

  handleOnClick=()=>{
   //fetchData and here 
   this.setState({data})
  }

Upvotes: 1

LMulvey
LMulvey

Reputation: 1680

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.

Upvotes: 1

leogoesger
leogoesger

Reputation: 3840

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.

Upvotes: 1

Related Questions