I am using react-firebase-hooks
useList which wraps around onX(..)
listening to data in real time.
This is my insert method:
export const insertItem = () => {
let key = createUniqueId();
return set(ref(db, `chat/${key}`), {
chat_id: key,
})
.then((data) => {
push(ref(db, `chat/${data.key}/messages`),{
sender: "foo",
text: "hello"
})
})
.catch((error) => {
return error;
});
};
This is my component:
export const Chat = () => {
const [snapshots, loading, error] = useList(ref(db, 'chats'));
let chats = snapshots.map(data => {
let chat = data.val()
let checkNewMessage = Object.keys(chat["messages"]);
let newest = checkNewMessage[checkNewMessage.length - 1];
let item = chat["messages"][newest]
return (
<div>{item.text}</div>
)
})
return (
<div>{chats}</div>
)
};
Databse:
When it comes to rendering the chat along with the message I run into two issues.
Cannot convert undefined or null to object
Can’t perform a React state update on an unmounted component. This is
a no-op, but it indicates a memory leak in your application. To fix,
cancel all subscriptions and asynchronous tasks in a useEffect cleanup
function.
From my understanding, I think the reason why it is still null/undefined is due to the message item has not yet been created due to async/promise actions. How can I correctly wait for all db changes to be inserted?
Once I refresh my page it renders it as expected. without any errors.