Reputation: 3411
this.state = {
post: {
question: '',
img: '',
postId: '',
userId: ''
},
feed: [],
}
What is the best practice for adding an object to an array.
Upvotes: 0
Views: 117
Reputation: 2384
First you need some corrections with state
:
this.state = {
posts: [],
feeds: [],
}
In a future Posts will be an Array of Objects
for example:
this.state = {
posts: [
{ postid: 1, question: "question" },
{ postid: 2, question: "question" }
]
}
Use this.setState
to add a new post to posts, also keep in mind the state
is immutable:
const newpost = { id: 1, question: "question" };
this.setState({
posts: this.state.posts.concat(newpost)
// or with rest operator posts: [...this.state.posts, newpost]
})
More about state
React State
An example JSFiddle
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
feed: [],
}
}
getName = () => {
const names = ['One', 'Two', 'Three', 'Four', 'Five', 'Six']
const random = Math.floor(Math.random() * names.length);
return names[random]
};
getId = () => Math.floor(Math.random() * (9999-1)) + 1;
makePost = () => ({ id: this.getId(), name: this.getName() });
createPost = () => {
this.setState({
// Rest operators ensure a new object with merged properties and values.
// Requires the "transform-object-rest-spread" Babel plugin
posts: [...this.state.posts, this.makePost()]
// Or like this: this.state.posts.concat(this.makePost())
})
};
render() {
return (
<div>
<button onClick={this.createPost}>Create Post</button>
<pre>
{JSON.stringify(this.state, null, 2)}
</pre>
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById('container')
);
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Upvotes: 2