I put a console.log() in and it traces out the poll every 2 seconds with the MongoDB collection output as an array. That is working as intended BUT stops polling after a post has just been made.
I usually get that error when the array variable (data in your case) is undefined. Also , is data coming in as prop ? It looks like it is being set as a state
Yes it’s loading the data from axios.get(this.props.url) and then immediately set the state to populate the list, which works as intended on first load:
Ok but shouldn’t your map function be then be like this.state.data.map? Or are you passing data as a prop to another function ? Assuming you have data declared in your constructor’s state
This might be a dumb question, but is the component that’s doing the loading getting unmounted after a post is made? Maybe posting a link to a github repo could help, since there seem to be several different components in play here.
The response you’re getting from this POST request is not an array that you can the iterate through. Instead, it’s {"message":"Comment successfully added!"}, so don’t set your state here. You can check the network tab in Chrome to confirm.
@sa-mm That’s very helpful thanks. The first part is very similar to the basic idea behind setting intervals and clearing them in vanilla JS. It’s just wrapped within component lifecycle hooks.
I found the problem area in commentBox.js, the author had called setState and passed this.state.data inside the catch error block…
…might be a way to combine your solution with the author’s. I feel like the author’s original solution might lead to some flickering if the post request does return an error.
Also, what happens if that catch block does get called? Does the user’s comment just disappear?
@sa-mm Thanks, I don’t think the 2nd line in the catch error block should be there. It is just providing a fallback in case there’s some error with the user input. I could do with being able to add form field validation in a React way.