Reputation: 4253
I am using firebase with react to get some posts. I would like to update posts on the screen in realtime if anything changes on it using react.
I print this posts like this:
return (
<>
{posts.map((post, index) => {
//firebase to check updates
var postref = firebase.database().ref('/posts/' + post.key).orderByKey();
postref.on("value", function(snap) {
var changedPost = snap.val();
console.log("The updated post title is " + changedPost.titulo);
});
return <Post key={post.key} id={post.key} ref={ref} img={post.img} titulo={post.titulo} />
})}
</>
)
}
in the middle I have firebase, to check if any update has been made, for example if someone edited the title. It is working, console.log the title if it changes.
The problem is, how can I update this edited title to the user in realtime using react? Should I create a state? array of states for each post? what can I do to update post.titulo if any changes occurs?
thanks
Upvotes: 0
Views: 58
Reputation: 2877
For making react component re-render, you need either change state or props to make it draw UI again with a new context. I don't sure what exactly posts
is and how do you fetch it (maybe using custom hook there is the best practice...), but adding a possible way to do it
const [ uiPosts, setUIposts ] = useState({})
{posts.map((post, index) =>
setUIposts({...uiPosts, [post.key]: ...post})
var postref = firebase.database().ref('/posts/' + post.key).orderByKey();
postref.on("value", function(snap) {
setUIposts({...uiPosts, [post.key]: ...post})
});
return <Post titulo={uiPosts[post.key].titulo} />
})}
Upvotes: 1