Reputation: 9780
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
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 unlessshouldComponentUpdate()
returns false. If mutable objects are being used and conditional rendering logic cannot be implemented inshouldComponentUpdate()
, callingsetState()
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 causerender(
) to be called on the component, skippingshouldComponentUpdate()
. This will trigger the normal lifecycle methods for child components, including theshouldComponentUpdate()
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