Currently trying to learn react with firebase and keep getting some minor roadblocks.
As of now, I am trying to render the data from a selected item in a new page. The index page contains the following:
renderPosts(){
return Object.keys(this.state.posts).map((post, index)=>(
<div key={index} className="thumbnail">
<h2>
<Link to={`/view/posts/${post}`}>
{this.state.posts[post].title}
</Link>
</h2>
<p>{this.state.posts[post].body}</p>
</div>
));
}
render() {
return (
<div>
<div>
{this.renderPosts()}
</div>
<View/>
</div>
)
}
As you can see it appends the ID of that post into the link so what I want to do now is to reach back into firebase and render the corresponding data of the item with that ID alone in a new page.
The ViewPost.js file as so:
constructor(props){
super(props);
this.state = {
title: '',
body: '',
};
}
componentDidMount(){
database.on('value', snapshot => {
this.setState({
post: snapshot.val()
});
this.props.match.params.postId;
});
}
render() {
return (
<div >
{this.state.props.title}
</div>
)
}
Can you please show me what I’m doing wrong and how to do it?
There a missing piece in your example, your router. First, you need to add a new route to the router.
<Route path='/view/posts/:postId' component={ViewPost}/>
This is the route then you are telling the router you want to go to in the link tag in the render method you created:
<Link to={`/view/posts/${post}`}>
I am assuming the component you want to render when you go to that link is the code you wrote in ViewPost.js sample above. If you import this component as ViewPost
in your router file it should work now.
Click on the link, and it will load up that component.
Next, inside the component, you want to call the data associated with the key you see in the URL. The grab the key value form the URL you use this.props.match.params.postId
.
Now that you have access to the key value you can do a regular firebase call in componentDidMount:
componentDidMount(){
database
.ref(`posts/${this.props.match.params.postId}`)
.on('value', snap => {
this.setState({post: snapshot.val()});
})
}
I hope that made sense. First make a route, then get the value of the key from the URL, then use the key value to do a database request inside the component that you end up at.