Gergő Horváth
Gergő Horváth

Reputation: 3705

Is it efficient to dispatch data from just firebase listeners?

const listRef = firebase.database().ref();

const reducer = (state = {}, action) => {
  switch (action.type) {
    case: "GET_LIST" : {
      const { list } = action;

      return { list };
    };
    case: "ADD_ELEMENT" : {
      const { elementId } = action;

      return { ...state, [elementId]: true };
    };
    default : return state;
  };
};

const getList = list => ({
  type: "GET_LIST", list
});

const addElement = elementId => ({
  type: "ADD_ELEMENT", elementId
})

const getListFromDb = () =>
  async dispatch => listRef.once("value", snap => {
    dispatch(
      getList(
        list
      )
    );
  });

const listenToElementAdded = () =>
  async dispatch => listRef.on("child_added", ({ key: elementId }) => {
    dispatch(
      addElement(
        element
      )
    );
  });

const addElementToDb = () =>
  async dispatch => dispatch(
    addElement(
      listRef.push().key
    )
  );

const Component = ({
  list,

  getListFromDb,
  listenToElementAdded,
  addElementToDb
}) => {
  useEffect(() => getListFromDb(), []);
  useEffect(() => listenToElementsAdded());

  return (
    <div>
      { Object.keys(list).map(id => <p>{id}</p>) }
      <p onClick={addElementToDb}>Add</p>
    </div>
  );
};

const mapStateToProps = list => ({ list });

const mapStateToProps = {
  getListFromDb,
  listenToElementAdded,
  addElementToDb
};

export default connect(mapStateToProps, mapStateToProps)(Component);

The simplified example above shows what I mean. The question is: is firebase listeners fast enough to replace data pre-dispatching with redux?

If we want to build an application, where we want to refresh data live which comes from outside, listeners can help. But if we pre-dispatch the data we get, we're dispatching twice. Also, if we're using just listeners, and dispatch from there, it can make the code, and the working of it much more cleaner. But what if we have loads of data inside the database? Will the listeners be fast? Is it efficient to handle dispatching just through listeners, or is it worth for it to pre-dispatch in place?

Upvotes: 1

Views: 188

Answers (1)

infamoustrey
infamoustrey

Reputation: 718

I would recommend having your firebase event listeners call redux-thunk actions that then manipulate and dispatch data to your application. There's nothing wrong with that if done properly.

However consider some not better but different approaches.

There's react-redux-firebase which allows for tight-nit coupling with your applications store. However if that is too much of an integration (you're literally melding your app with firebase), then go with the former.

Regardless I recommend you search some more for content about using firebase with your redux app.

Upvotes: 2

Related Questions