0

I have written a method like below but i am noticing my API is getting called multiple times. I am calling my API inside componentDidMount().

class User extends Component {
  state = {
    cardData: [],
  };

  userDetails = async () => {
    const data = await fetchUserDetails();
    if (data) {
      const url = data.baseUrl;
      const getDetails = Object.values(data).map((users) => users.user);
      this.setState({ cardData: getDetails });
    }
  };

  componentDidMount() {
    this.userDetails();
  }
}

How can i overcome this?

techie_questie
  • 1,434
  • 4
  • 29
  • 53
  • I can't see anything here that'd cause a double render. I assume `fetchUserDetails` is just some function that returns a promise that does an API call? Also is there any other code for the component that's omitted? – Jayce444 Feb 10 '20 at 04:56
  • fetchUserDetails is just some function that returns a promise that does an API call?- Yes. Haven't omitted anything, i thought its because of componentDidMount. – techie_questie Feb 10 '20 at 04:57
  • And how do you tell it's double rendering, is there something `fetchUserDetails` that logs when it's called? Also, you're not rendering 2 `` components somewhere I assume – Jayce444 Feb 10 '20 at 05:00
  • I am seeing the api calls is getting called multiple times in my network tab. – techie_questie Feb 10 '20 at 05:02
  • Look for a reason componentDidMount() is running multiple times. Is something in the parent component of User re-rendering the User component? Maybe because of a state change? – Sydney Y Feb 10 '20 at 05:02
  • `componentDidMount` only ever runs ONE time during the life cycle of the component, *no exceptions*. If the `` component was re-mounted that would cause it to fire again, but without seeing how the User component is being rendered I can't say – Jayce444 Feb 10 '20 at 05:04
  • I am only adding a route to a USER component in my APP.js – techie_questie Feb 10 '20 at 05:06
  • Add log in `componentDidMount()` to make sure the network call is really coming from that function. – boosted_duck Feb 10 '20 at 05:07
  • Can u plese try shouldCompontUpdate () function return true or false base on api call – venkatramanan Feb 10 '20 at 05:12

0 Answers0