Reputation: 372
I am learning the concepts of Redux. From what I understand, reducers are not supposed to mutate state, they return a new state with mutations applied. They are also not supposed to (or maybe even can't?) dispatch other actions.
Given those limitations, that pretty much leaves you with the action creators, middleware, or your React components (if using Redux with React) to call your business logic. So, what I'm trying to do is use Firebase, the wall I've hit, and the questions I have are the following:
Finally I ended up following the @ampersand suggestion. I made a module with all the listeners of Firebase application. I import in the Firebase module a dispatcher.js
file, that is composed by dispatcher function like these:
import store from '../store';
import * as actions from './index';
export function addUserMessage(text) {
store.dispatch(actions.addUserMessage(text));
}
export function addResponseMessage(messageObj) {
store.dispatch(actions.addResponseMessage(messageObj));
}
What I was not understanding was how to dispatch action from an external module. Now I have the concepts clear.
Upvotes: 0
Views: 1493
Reputation: 11
To tack onto @chautelly's response, generally services in react/redux are just modules—create your firebase instance inside a standalone module, export the appropriate object from it, and import where needed.
database.js
import firebase from 'firebase';
firebase.initializeApp({
apiKey: 'api key',
authDomain: 'db_name.firebaseio.com',
databaseURL: 'https://db_name.firebaseio.com/'
});
const database = firebase.database();
export default database;
Upvotes: 1
Reputation: 467
I'm not familiar with Firebase, but I think middleware is most likely the answer here.
You can write a simple middleware that has access to your Firebase instance and will dispatch these message to the Redux store.
// firebase-middleware.js
export default function createFireBaseMiddleware (firebaseInstance) {
return store => dispatch => {
fireBaseinstance.on(message => {
dispatch({
type: 'FIREBASE_MESSAGE',
payload: message,
})
})
return action => {
if (action.type === 'TALK_BACK_TO_FIREBASE' {
firebaseInstance.postMessage(action)
}
// Let the action continue down the path of middleware to the store
return dispatch(action)
}
}
}
// createStore.js
export default createStore(
reducer,
applyMiddleware(createFireBaseMiddleware(myfirebaseInstance)
)
Upvotes: 1