FormidableLabs / redux-little-router

A tiny router for Redux that lets the URL do the talking.
MIT License
1.04k stars 114 forks source link

Add param/query transformation function to route definitions #214

Closed drKnoxy closed 6 years ago

drKnoxy commented 7 years ago

It would be sweet if there were transformation functions that could be applied to the parameters of the url or the query based on route

something like:

const routes = {
  '/house/:id': {
    transform({ params, query) {
      return {
        params: parseInt(params.id, 10),
        query: {
          ...query,
          sort: sortOptions.includes(query.sort) || 'popularity',
          features: query.features ? query.features.split(',') : [],
      };
    }
  }

If this sounds good, and you would point me at some files i'd be glad to start a branch.

dpwrussell commented 7 years ago

Unless I've misunderstood the purpose of this, I think you might be better served with selectors than a transformation. That way the true state remains if you were to need it for something else.

As we already have redux, and redux-little-router takes care of making sure that is up to date (#211 aside) with the query parameters, this is the minimum state. If you then want to get query parameters with a certain transformation, you could write (untested):

import { createSelector } from 'reselect';

const getRouter = state => state.router;

export const getRouteQueryFeatures = createSelector(
  [ getRouter ],
  router => router.query && router.query.features ? router.query.features.split(',') : []
);

Then in a component:

import { getRouteQueryFeatures } from './selectors';

const FeatureList = props => <ul>{ props.features.map(feature => <li>{ feature }</li>) }</ul>;

export default connect(state => ({ features: getRouteQueryFeatures(state) }))(FeatureList);
drKnoxy commented 7 years ago

Yeah, i thought it just looked nicer to colocate the "type transformations" with the route, especially for params. I prefer the idea of storing /post/:id /post/123 in redux as number 123 instead of string 123.

dpwrussell commented 7 years ago

I'm actually not sure why it is stored in redux at all when it could be calculated by a selector from the route.

tptee commented 6 years ago

Yep, I agree with @dpwrussell that selectors are the tool for this job 😃