hirviid/react-redux-fetch

Is there a standard way to transform data before setting state?

Closed this issue · 1 comments

Apologies if this is the wrong place to ask.

I'm trying to understand if there is a standard pattern for transforming the response data before setting it in my component's state, or, if it should just be handled by the component itself in the render method

Hi @colinhowe

I would write a selector for that.

// selectors.js
import sortBy from 'lodash/sortBy';
import { selectors } from 'react-redux-fetch';
import { createSelector } from 'reselect';

const getTodos = selectors.getRepository('todos'); // 'todos' is the name of your resource

export const getTodosSortedByDate = createSelector([getTodos], (todos) => {
  // do your transformations
  return sortBy(todos, ['date']);
});
// MyComponent.js
// ...
import { getTodosSortedByDate }  from './selectors';

class MyComponent extends React.Component {
  // ...
}

const mapStateToProps = (state) => ({
  todosSorted: getTodosSortedByDate(state), // Uses 'this.props.todosSorted' for the transformed response.
});

export default reduxFetch((props) => ([
  {
    resource: 'todo',
    request: {
      url: '/api/todos'
    }
  }
], mapStateToProps)(MyComponent);

Does this answer your question?