I'm currently working on a react-native
app with a chat feature. I'm using redux
to store my states. So after pressing the send-button to send a message, an action is called to send the message to firebase and show it on the screen afterwards.
My current problem is that while the action I called dispatches the right type/payload, another type/payload is also being dispatched, which is not being dispatched in the called action. Apparently somehow another action is being called containing the type/payload.
The code of the action which is not being called is the following:
const getChatData = (chatIDs, userName, uid) => async dispatch => {
console.log('hasdhkhwerljlkbgkanndhadndngknnjnjsnfjskdnfjsuvhshdifhuishiduhfuishdkfnkjsndf')
const chatData = []
for (const key of chatIDs) {
[...]
// get message
firebase.database().ref('messages/' + key)
.orderByChild('timestamp').limitToLast(1)
.on('child_added', snapshot => {
const { text, timestamp, user } = snapshot.val();
const { name } = user;
chatData.push({ key, members: displayNameArray, text, timestamp, name })
dispatch({
type: GET_CHAT_DATA,
payload: chatData
})
})
})
}
}
As I said, the type GET_CHAT_DATA
is being dispatched eventhough this action is not being called. Furthermore, the console.log doesn't show the long test message, which should mean that this action is not being called, right?
What could cause this weird behaviour?
Thank you so much!
So the thing is even though you did not execute the function but in there you registered an event on firebase
.on('child_added', snapshot => { })
Now whenever this child_added
event will trigger, the handler will be executed.
That is why your dispatcher is running because its inside the event handler.
firebase.database().ref('messages/' + key)
.orderByChild('timestamp').limitToLast(1)
.on('child_added', snapshot => {
// this is the event handler which is executing
// when the "child_added" event is triggered
const { text, timestamp, user } = snapshot.val();
const { name } = user;
chatData.push({ key, members: displayNameArray, text, timestamp, name })
dispatch({
type: GET_CHAT_DATA,
payload: chatData
})
})
})