Riya Kapuria
Riya Kapuria

Reputation: 9780

How to cause the component to re-render after an ajax request

Rerendering same component inside one function in ReactJs. I'm adding comment and now after that I want to rerender the same component. Can anyone help?

commentPost() {...
    axios.defaults.headers.common['Authorization'] = getToken;
        axios.post(apiBaseUrl+'v1/comments/post-comment',input)
        .then(function (response) {
          console.log("Comment Post",response);
          //here I want to rerender this component itself
        })
        .catch(function (error) {
          console.log(error);
        });...

Upvotes: 0

Views: 2112

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281744

There are two things that you can do to cause the same component to render

First: Update a state of the current component using the setState method.

setState() will always lead to a re-render unless shouldComponentUpdate() returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

Second: You can call forceUpdate in case you do not want to update any state of the current component. You can call it like this.forceUpdate().

Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes.

Assuming that you are performing an async request from which you are getting a response you would want to update the component's state with the data that you got and hence setState would be the way forward for you

Upvotes: 3

Related Questions