Is it possible to re-run componentDidMount when executing a function? - reactjs

At the moment my componentDidMount retrieves jobs from the database and displays them on my main page.
I created a function called deleteJob, which deletes a Job. The problem is that I have to refresh the page to see the changes.
Is it possible to see the change immediately without refreshing the page? I thought this could be done if I somehow made componentDidMount run again when executing the function
Please let me know if this is possible.
componentDidMount() {
axios.get("/getJobs").then(result => {
console.log("appear!");
this.setState({ jobData: result.data }, () => {
console.log(this.state);
});
});
axios.get("/getServices").then(result => {
this.setState({ serviceData: result.data }, () => {
});
});
deleteJob() {
axios.get("/deleteJob/" + this.props.id).then(result => {
});
this.props.close()
}

Why do you see the change? Because it updates the state.
So you should update your state when you delete a job.
Better, extract the axios "getJobs" to a method of the class and then call it in componentDidMount, and in deleteJobs.
This way, you will refresh your state at each action.

What you can do in this case is fetch the jobs again after deleting the job, also you can separate your functions by their behavior so you can call them in different cases
componentDidMount() {
getJobs();
getServices();
}
getJobs() {
axios.get("/getJobs" + this.props.id).then(result => {
this.setState({ jobData: result.data }
});
}
getServices() {
axios.get("/getServices").then(result => {
this.setState({ serviceData: result.data }
});
}
deleteJob() {
axios.get("/deleteJob/" + this.props.id).then(result => {
getJobs(); // get jobs again after deletion
});
this.props.close()
}

You can just filter the state with the id which you are deleting
lets say
componentDidMount() {
axios.get("/getJobs").then(result => {
this.setState({ jobData: result.data }, () => {
console.log(this.state);
});
}
you can call a delete method on Click of a button
//Assuming the delete request is post Id
deleteJob =(id)=>{
deleteJob() {
axios.post("/deleteJob/" ,+ id)
//this will filter out the deleted job from existing state
let filteredJobs = this.state.jobData.filter(data=>data.id===id)
this.setState({
jobData:filteredJobs
)}
}
This will re-render the component without refreshing page and no API calls :)

Related

How to set state of other component inside an axios get method in react?

I'm using class-based components in react. I have few components named as follows: Blogs, BlogsClient, BlogCard. When Blogs mounts I make a call to a function inside BlogClient named as getBlogContent to fetch me data using axios.
setBlogs = (blogs) => {
this.setState({ "blogs": blogs });
}
componentDidMount() {
getBlogContent(this.setBlogs);
}
where getBlogContent is:
let getBlogContent = (setBlogs) => {
store.set('loaded', false);
axios.get(ADMIN_URL + '/getAllBlogs')
.then(response => {
store.set('loaded', true);
setBlogs(response.data.Response);
})
.catch(error => {
store.set('loaded', true);
store.set('errorMessage', error);
})
}
I'm able to fetch data and update my state properly. But If there comes any error inside Blogs or BlogCard(which is called inside Blogs) it goes inside the catch of getBlogContent whereas it should be only responsible for catching Axios error. What am I missing here?
Ok, so it's hard to tell without knowing these errors..
But nonetheless, you should avoid setting the component's state outside that component. So, your code'd become:
componentDidMount() {
const blogContent = getBlogContent();
if (blogContent !== 'error'j this.setBlogs(blogContent);
}
let getBlogContent = () => {
store.set('loaded', false);
return axios.get(ADMIN_URL + '/getAllBlogs')
.then(response => {
store.set('loaded', true);
return response.data.Response;
})
.catch(error => {
store.set('loaded', true);
store.set('errorMessage', error);
return 'error';
})
}

Unable to setState regardless of making setState synchronous

I am learning about how to use synchronous setState but it is not working for my project. I want to update the state after I get the listingInfo from Axios but it does not work, the res.data, however, is working fine
class ListingItem extends Component {
constructor(props) {
super(props);
this.state = {
listingInfo: {},
open: false,
};
this.getListingData(this.props.itemId);
}
setStateSynchronous(stateUpdate) {
return new Promise((resolve) => {
this.setState(stateUpdate, () => resolve());
});
}
getListingData = async (item_id) => {
try {
const res = await axios.get(`http://localhost:5000/api/items/${item_id}`);
console.log(res.data);//it's working
await this.setStateSynchronous({ listingInfo: res.data });
// this.setState({
// listingInfo: res.data,
// });
console.log(this.state.listingInfo);//no result
} catch (err) {
setAlert('Fail to obtain listings', 'error');
}
};
I would be really grateful for your help!
Thanks to #PrathapReddy! I used conditional rendering to prevent the data from rendering before the setState is done. I added this line of code on the rendering part:
render() {
if (Object.keys(this.state.listingInfo).length === 0) {
return (
<div>
Loading
</div>
);
} else {
return //put what you want to initially render here
}
}
Also, there is no need to modify the setState, the normal setState will do. Hope this is useful!

React componentDidMount not setting states before page loads

Working on a MERN application, I have a componentDidMount that uses axios to retrieve from the backend some Ids and retrieve product info(prods) from the ids. However the states in my application are still empty when the page is loaded initially, instead I'll have to make a change to state before the states are set.
I believe it might have something to do with having an array mapping in the componenDidMount, I could change the backend so in node. However i would like to see if anything could be done in the frontend first.
componentDidMount() {
axios
.get("/api/featureds")
.then(response => {
this.setState({
featureIds: response.data
});
response.data.map(({ prodId, _id }) =>
axios
.get("/api/prods/" + prodId)
.then(response => {
if (response.data == null) {
} else {
this.state.featureTempList.push(response.data);
}
})
.catch(error => {
console.log(error);
})
);
this.setState({
featureProds: this.state.featureTempList
});
})
.catch(error => {
console.log(error);
});
}
Why are you trying to set state like this?
this.state.featureTempList.push(response.data)
State should be set by this.setState().
So you can try doing this:
this.setState((oldState) => ({
featureTempList: oldState.featureTempList.push(response.data)
});
Just remember to set featureTempList to state when you initialize:
state = {
featureTempList: []
}

where should i call the setintreval in react

I am trying to call getSession() every 5sec of delay. But in initial render i would like to call this function and execute immediately.
According to my below code, in the initial render itself it is using the delay of 5sec to display the output.
How can i achieve the following:
1. Initial render should be done immediately
2. after every 5sec getSession() should be called as well.
Current Results:
It is taking 5sec delay to display in initial render.
Expected results:
Initial render should be done immediately.
componentDidMount() {
this.getSession();
}
getSession() {
var path = "Sharing.aspx/GetSessions";
setInterval(() => {
axios
.post(path, { withCredentials: true })
.then(response => {
let element = response.data.d;
this.setState({
sessions: element
});
})
.catch(error => {
this.setState({
Errors: error
});
console.error(error);
});
},5000
);
}
render() {
return (
<div>
{this.renderSessionDetails()}
</div>
);
}
Expected results:
Initial render should be done immediately.
After every 5sec getSessions() should be called.
I would do something like this:
const INTERVAL = 6000;
class Component extends React.Component {
componentDidMount() {
this.getSession();
this.intervalId = window.setInterval(() => this.getSession(), INTERVAL);
}
componentWillUnmount() {
window.clearInterval(this.intervalId);
}
getSession() {
var path = "Sharing.aspx/GetSessions";
setInterval(() => {
axios
.post(path, { withCredentials: true })
.then(response => {
let element = response.data.d;
this.setState({
sessions: element
});
})
.catch(error => {
this.setState({
Errors: error
});
console.error(error);
});
}, 5000);
}
render() {
return <div>{this.renderSessionDetails()}</div>;
}
}
ComponentDidMount will be called only once, and at that point, you call the first getSession call, and start the interval.
An important thing to bring attention to is the call to window.clearInterval when the component gets unmounted. This is to make sure that interval doesn't keep running eternally, and worst, that more than one interval run in parallel after having this component mount a couple of times.
I hope it helps.
You could go about refactoring your code to look like that, in order to avoid waiting initially for those 5 seconds. The refactor is mainly about extracting the fetching logic away from the timer implementation. Please note that inside componentDidMount() we first call this.getSession() immediately, which is fine because we eliminated the intervals from it. Then we dispatch the intervals.
class Component extends React.Component() {
intervalId = null
componentDidMount() {
this.getSession()
this.intervalId = setInterval(() => this.getSession(), 5000)
}
componentWillUnmount() {
if (this.intervalId) {
clearInterval(this.intervalId)
}
}
getSession() {
var path = 'Sharing.aspx/GetSessions'
axios
.post(path, { withCredentials: true })
.then(response => {
let element = response.data.d
this.setState({
sessions: element
})
})
.catch(error => {
this.setState({
Errors: error
})
console.error(error)
})
}
render() {
return <div>{this.renderSessionDetails()}</div>
}
}
I would also try to make sure we're not running into race conditions here. But, if you're sure your requests never take more than 5 seconds -- it should be fine. Hope it helps!

Race condition in React setState and Promise

In my Context I have a LocalFunction that returns a promise.
LocalFunction: () => Promise<void>
LocalFunction: () => {
return externalCall.getBooks().then((books) => {
this.setState({ Books: books })
})
}
I can call this function in another component based on the updated Books object in the Context state like:
this.props.LocalFunction().then(() => {
// do something with this.props.Context.Books
})
But I know React updates states in batches. So could I run into a race condition when calling LocalFunction without the Books state being updated with the new books?
I know a way to avoid it is to wrap LocalFunction in a new Promise and resolve it in this.setState({ Books: books }, resolve), but I wanna avoid doing that if possible.
How about to use async/await?
LocalFunction: async (needUpdate = false) => {
const result = await externalCall.getBooks();
if(needUpdate){
this.setState({ Books: result })
}
return result;
}
this.props.LocalFunction().then((res) => {
console.log(res)
// do something with this.props.Context.Books
})
When you need to update state
LocalFunction(true)

Resources