When I add data to the table it does not get populated with the new record. I created a list and displayed it to see if it populates the new record, it seems to have updated there. I add a console.log to the componentWillReceiveProps function to see if the list updates with the new record, the list does get updated but the table never updates. Fairly new to react, not sure what I am missing.
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/postActions';
import MaterialTable from 'material-table';
class Posts extends Component {
componentWillMount() {
this.props.fetchPosts();
}
componentWillReceiveProps(nextProps) {
if(nextProps.newPost) {
this.props.posts.unshift(nextProps.newPost);
}
}
render () {
const postItems = this.props.posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
));
return (
<div>
<div>
<h1>Posts</h1>
{postItems}
</div>
<div style={{marginLeft:'15px',marginRight:'15px'}}>
<div style={{ maxWidth: "100%" }}>
<MaterialTable
title="Users List"
columns={[
{ title: 'User Name', field: 'id' },
{ title: 'Email', field: 'title' },
]}
data={this.props.posts}
/>
<br/><br/><br/>
</div>
</div>
</div>
);
}
}
Posts.propTypes = {
fetchPosts: PropTypes.func.isRequired,
posts: PropTypes.array.isRequired,
newPost: PropTypes.object
}
const mapStateToProps = state => ({
posts: state.posts.items,
newPost: state.posts.item
});
export default connect(mapStateToProps, { fetchPosts })(Posts);
You cannot set props from inside the component, only from outside. That's the difference between state and props (it's quite fundamental in React, read about it).
First, initialize the state in constructor:
constructor(props) {
super(props);
this.state = { posts: [] };
}
then, update the state when props change:
componentWillReceiveProps(nextProps) {
if(nextProps.newPost) {
let updatedPosts = this.state.props;
updatedPosts.unshift(nextProps.newPost);
this.setState({ posts: updatedPosts });
}
}
}
finally, use the state in your table:
...
data={this.state.posts}
...