Home » Javascript » Are Redux reducer useless with firebase (except FETCH one)?

Are Redux reducer useless with firebase (except FETCH one)?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am learning using react/redux for the front end and firebase for the back-end.
I first begin to develop a CRUD app only with React/Redux.
And now, I am adding the backend using firebase.

I am asking myself if all my reducers except FETCH_POSTS one become useless’ because of the real-time database functionality.

In fact, in this example from stephen grider (js teacher), we can work with only one reducer (source).

//reducers/posts.js:

import _ from 'lodash';
import {
  FETCH_POSTS,
  CREATE_POST,
  DELETE_POST
} from '../actions/types';

export default function(state = {}, action) {
  switch (action.type) {
    case FETCH_POSTS:
      return action.payload;
    case CREATE_POST:
      return { ...state, ...action.payload };
    case DELETE_POST:
      return _.omit(state, action.payload);
  }

  return state;
}

//actions/index.js:

import Firebase from 'firebase';
import _ from 'lodash';
import {
  FETCH_POSTS,
  DELETE_POST,
  CREATE_POST
} from './types';

const Posts = new Firebase('https://fbredux.firebaseio.com/');

export function fetchPosts() {
  return dispatch => {
    Posts.on('value', snapshot => {
      dispatch({
        type: FETCH_POSTS,
        payload: snapshot.val()
      });
   });
  };
}

export function createPost(post) {
  return dispatch => Posts.push(post);
}

export function deletePost(key) {
  return dispatch => Posts.child(key).remove();
}

My question is: do we always have a benefit to call reducers while firebase is real time and have an offline mode?

And if we decide to work with reducer, how do we prevent issues like this scenario:

  1. deletePost action call Posts.remove(id)

  2. Firebase remove the post and notify the FETCH_POSTS reducer

  3. redux update the store

  4. Then, deletePost dispatch a new action {type:DELETE , payload:id}

  5. The reducer need to access to the post(id) value —> Error because the value is already deleted

Answers: