question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Network history proposal

See original GitHub issue

Hello !

First of all thank you for this package. Our application has many api requests calls and this is going to make our life much simpler.

After playing with your library we realized we could make something we called “network history”. It is basically a root reducer which takes all the actions (success, error, request) and with that it fills a network tree in the state that later we use to populate our app with selectors.

Here is the code I have so far:

import {createRequestInstance, watchRequests} from "redux-saga-requests/src";
import {isRequestAction} from "redux-saga-requests/src/sagas";
import axiosConfig from './axiosConfig'

const initialState = {};

/**
 * All network response actions has meta.request object in the payload
 */
const isNetworkResponseAction = action => 
  action.payload
  && action.payload.meta
  && action.payload.meta.request

/**
 * A success network action always has data in the meta
 */
const isSuccessAction = action => isNetworkResponseAction(action) && action.payload.data;

/**
 * An error network action always has error in the meta
 */
const isErrorAction = action => isNetworkResponseAction(action) && action.payload.error;

/**
 * REDUCER
 */
export default function network(state = initialState, action) {

  if (isRequestAction(action)) {

    const {type} = action;
    return {
      ...state,
      [type]: {
        ...state[type],
        fetching: true,
      },
    }
  }
  if (isSuccessAction(action)) {

    return {
      ...state,
      [action.payload.meta.type]: {
        fetching: false,
        data: action.payload.data,
        error: '',
      },
    }
  }
  if (isErrorAction(action)) {
    return {
      ...state,
      [action.payload.meta.type]: {
        ...state[action.payload.meta.type],
        fetching: false,
        error: 'Error',
      },
    }
  }
  //We can also have _ABORT action but we still not need it

  return state;
}

/**
 * SELECTORS
 */

export const selectNetworkResource = (state, resource: string) => state.network[resource] && state.network[resource].data

/**
 * LISTENERS
 */
export function* networkListeners() {
  yield createRequestInstance(axiosConfig)
  yield watchRequests();
}

After adding this network reducer in the root reducer with combineReducers we have a tree like this when we have one success call: webpack_app

So now we can use a selector in mapStateToProps to access the data:

const mapStateToProps = state => ({
  products: selectNetworkResource(state, PRODUCTS_REQUEST) || [],
});

We do this in orther to get rid of all the network related logic, in you example this:

- const booksReducer = (state = defaultState, action) => {
-     switch (action.type) {
-       case FETCH_BOOKS:
-         return { ...defaultState, fetching: true };
-      case FETCH_BOOKS_SUCCESS:
-      case success(FETCH_BOOKS):
-         return {
-           ...defaultState,
-           data: { ...action.payload.data },
-         };
-      case FETCH_BOOKS_ERROR:
-      case error(FETCH_BOOKS):
-         return { ...defaultState, error: true };
-       default:
-         return state;
-     }
-   };

As you see in the network reducer we don’t have an easy way to know which actions are SUCCESS, ERROR, ABORT…

  • Is there an easy way to know that?
  • Are you interested to have this ‘network history’ like this? If so I will be glad to submit a PR 😃

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:26 (14 by maintainers)

github_iconTop GitHub Comments

2reactions
klis87commented, Nov 6, 2017

If I understand your approach correctly, I believe that it’s not kept in the state.

If you want to preserve the data, you could just allow requestReducer to save data as data => data, (this would be the default, but we could make it as configurable by passing processData callback to config of requestReducer.

In my example, only state for FETCH_BOOKS was kept in state. But you could easily track CREATE_BOOK as well by creating another reducer:

const newBookReducer = requestReducer({ actionType: 'CREATE_BOOK' });

And, if you wanted to keep track of all requests, you could use a helper I suggested in a previous post:

const getNetworkReducers = actionTypes => (
  actionTypes.reduce((prev, current) => {
    return { ...prev, [current]: requestsReducer(current) };
  }, {})
);

const network = combineReducers(getNetworkReducers([PRODUCTS_REQUEST, OPTIONS_REQUEST]));

Perhaps the issue at hand is that I’m giving the “raw” response from the server excessive importance, and should instead not bother with recording it. What do you think?

It depends on your use case. If you need it just for logging purposes, maybe it would be better to set some redux-saga-request interceptor? Or if you could need it later, then reducers are the best place to keep it. And with getNetworkReducers, you could easily achieve that.

Also, in the case where multiple endpoints could alter the state, for example, of known books (fetch books and fetch books by author), would you take an approach similar to mine or do you have another strategy in mind?

I like your approach, with my version of requestReducer, I just woudn’t need handle FETCH_BOOKS cases, as this would be handled by the requestReducer.

1reaction
ebardajizcommented, Nov 2, 2017

Good point. Again, it’s why I preferred @poteirard’s initial approach. There, the reducer we’re passing to the HOR does not need to know of the outside world. It can continue performing it’s duties independent of any particular library which tries to expand it.

This also allows for better adoption of libraries which approach HORs in this way.

Read more comments on GitHub >

github_iconTop Results From Across the Web

The original proposal of the WWW, HTMLized
This proposal concerns the management of general information about accelerators ... is a multiply connected "web" whose interconnections evolve with time.
Read more >
Sample Thesis Proposals - History - Williams College
Lanfranc of Bec: Confrontation and Compromise Imperial Expansion and the Evolution of the South and Southeast Asian economies. Nantucket's Role in the War ......
Read more >
Preserve Our Technological History: A Proposal | Network Computing
I propose a broad movement to collect and preserve the books and other physical materials that document the creation and development of 20th...
Read more >
THESIS PROPOSAL - College of Science and Engineering
This allows the users to move around in a limited area while being still connected to the network. Thus, WLANS combine data connectivity...
Read more >
The Web at 25: Revisiting Tim Berners-Lee's Amazing Proposal
A graphic from Tim Berners-Lee's 1989 proposal for what became ... Several other early dates in web history matter as much as this...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found