How to use reselect - 10 common examples

To help you get started, we’ve selected a few reselect examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mattermost / mattermost-redux / src / utils / helpers.ts View on Github external
//eslint-disable-line prefer-rest-params
            // apply arguments instead of spreading for performance.
            const result = Reflect.apply(func, null, arguments); //eslint-disable-line prefer-rest-params
            if (!shallowEqual(lastResult, result)) {
                lastResult = result;
            }
        }

        lastArgs = arguments; //eslint-disable-line prefer-rest-params
        return lastResult;
    };
}

// Use this selector when you want a shallow comparison of the arguments and you want to memoize the result
// try and use this only when your selector returns an array of ids
export const createIdsSelector = reselect.createSelectorCreator(memoizeResult);

// Use this selector when you want a shallow comparison of the arguments and you don't need to memoize the result
export const createShallowSelector = reselect.createSelectorCreator(reselect.defaultMemoize, shallowEqual as any);

// isMinimumServerVersion will return true if currentVersion is equal to higher or than the
// the provided minimum version. A non-equal major version will ignore minor and dot
// versions, and a non-equal minor version will ignore dot version.
// currentVersion is a string, e.g '4.6.0'
// minMajorVersion, minMinorVersion, minDotVersion are integers
export const isMinimumServerVersion = (currentVersion: string, minMajorVersion = 0, minMinorVersion = 0, minDotVersion = 0): boolean => {
    if (!currentVersion || typeof currentVersion !== 'string') {
        return false;
    }

    const split = currentVersion.split('.');
github Kaniwani / kw-frontend / app / features / user / selectors.js View on Github external
'kanjiSvgDrawSpeed',
    ])
  )
);

export const selectUsername = createSelector(selectUserProfile, getBy('name'));
export const selectApiKey = createSelector(selectUserProfile, getBy('apiKey'));
export const selectUserLevel = createSelector(selectUserProfile, getBy('level', Number));
export const selectOnVacation = createSelector(selectUserProfile, getBy('onVacation', Boolean));

export const selectVacationDate = createSelector(
  selectUserProfile,
  getBy('vacationDate', dateOrFalse)
);

export const selectNextReviewDate = createSelector(
  selectUserProfile,
  // padded with 30 second safety net to ensure server is completely updated when we request new review count
  getBy('nextReviewDate', (date) => (date != null ? addSeconds(date, 30) : false))
);

export const selectFreshUser = createSelector(
  [
    selectNextReviewDate,
    selectLessonsCount,
    selectReviewsCount,
    getBy(['entities', 'reviews'], (x = {}) => Object.keys(x).length),
  ],
  (nextReviewDate, lessonsCount, reviewsCount, reviewEntitiesCount) => !nextReviewDate && lessonsCount && !reviewsCount && !reviewEntitiesCount
);

export const selectLastWkSyncDate = createSelector(
github ModelChimp / modelchimp / client / app / containers / ProjectPage / index.js View on Github external
);
  }
}

ProjectPage.propTypes = {
  projects: PropTypes.array,
  getProjectData: PropTypes.func,
};

export function mapDispatchToProps(dispatch) {
  return {
    getProjectData: () => dispatch(loadProjectData()),
  };
}

const mapStateToProps = createStructuredSelector({
  // repos: makeSelectRepos(),
  // username: makeSelectUsername(),
  loading: makeSelectLoading(),
  projects: makeSelectProjects(),
});

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

const withReducer = injectReducer({ key: 'project', reducer });
const withSaga = injectSaga({ key: 'project', saga });

export default compose(
  withReducer,
github Kaniwani / kw-frontend / app / common / oldSelectors.js View on Github external
import { createSelectorCreator, defaultMemoize } from "reselect";
import { isFinite, isEqual } from "lodash";
import { titleCase } from "voca";

import { SRS_RANKS } from 'common/constants';

import groupByRank from 'common/utils/groupByRank';
import dateOrFalse from 'common/utils/dateOrFalse';
import getSrsRankName from 'common/utils/getSrsRankName';
import filterRomajiReadings from 'common/utils/filterRomajiReadings';
import formatSrsCounts from 'common/utils/formatSrsCounts';
import formatUpcomingReviews from 'common/utils/formatUpcomingReviews';

// create a "selector creator" that uses lodash.isEqual instead of a shallow ===
export const createDeepEqualSelector = createSelectorCreator(defaultMemoize, isEqual);

export const selectIdFromMatch = (props) => +props.match.params.id;
export const selectCategoryFromMatch = (props) => props.match.params.category;
export const selectEntities = (state) => state.entities;
export const selectUi = (state) => state.ui;

export const selectUser = (state) => state.user;
export const selectProfile = createDeepEqualSelector(selectUser, (user) => {
  if (!user || !user.profile) {
    return {};
  }
  const { profile } = user;
  return {
    id: profile.id,
    name: profile.name,
    apiKey: profile.apiKey,
github coverhound / active-redux / src / query / utils.js View on Github external
import qs from 'qs';
import { createSelectorCreator, defaultMemoize } from 'reselect';

const isEqual = (a, b) => (
  typeof a === 'string' ?
    a === b :
    JSON.stringify(a) === JSON.stringify(b)
);

const createDeepEqualSelector = createSelectorCreator(
  defaultMemoize,
  isEqual,
);

/**
 * @alias module:active-redux.createQuerySelector
 * @function
 * @example
 *
 * import { createQuerySelector } from 'active-redux';
 * import { Comment } from '@models';
 *
 * const Comment = ({ comment }) =&gt; <p>{comment.body}</p>;
 *
 * // needed in order to have a unique selector per instance of the component
 * const mapStateToProps = () =&gt; {
github nick121212 / fx-schema-form / packages / fx-schema-form-react / src / hocs / data.tsx View on Github external
/**
     * 是否需要当前key对应的meta数据
     */
    meta?: boolean;
    /**
     * 设置当前key下所需要的meta的key值
     */
    metaKeys?: string[];
    /**
     * 是否获取meta的根节点
     */
    treeNode?: boolean;
}

// 自定义选择器创建函数
const fxSelectorCreator: any = createSelectorCreator(defaultMemoize, is);

export const name = "data";
export const hoc = (hocFactory: BaseFactory&gt;) =&gt; {
    return (settings: DataHocSettings = {
        data: true
    }) =&gt; {
        /**
         * 与reduce相关的数据操作
         * 获取formItemData数据
         * 获取formItemMeta数据
         */
        const getItemDataHoc = (parentKeys: string[], rootReducerKey: string[], keys: Array) =&gt; {
            /**
             * 获取FormItemData的数据
             * @param state 当前的state树
             */
github vlsergey / WE-Framework / src / core / selectors.js View on Github external
import { createSelector, defaultMemoize } from 'reselect';
import { DEFAULT_LANGUAGES } from 'utils/I18nUtils';

const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
const EMPTY_STRING = '';

const labelalikesFromEntity = entityElementName => entity => entity[ entityElementName ] || EMPTY_OBJECT;
const labelsFromEntity = labelalikesFromEntity( 'labels' );
const descriptionsFromEntity = labelalikesFromEntity( 'descriptions' );
const aliasesFromEntity = labelalikesFromEntity( 'aliases' );

/* 3 different instances of the same thing -- since cache size is 1 */
const allLanguagesFromLabels = defaultMemoize( labelalike => Object.keys( labelalike ) );
const allLanguagesFromDescriptions = defaultMemoize( labelalike => Object.keys( labelalike ) );
const allLanguagesFromAliases = defaultMemoize( labelalike => Object.keys( labelalike ) );

export const listLabelalikeLanguages = createSelector(
  entity => allLanguagesFromLabels( labelsFromEntity( entity ) ),
  entity => allLanguagesFromDescriptions( labelsFromEntity( entity ) ),
  entity => allLanguagesFromAliases( labelsFromEntity( entity ) ),
  ( fromLabels, fromDescriptions, fromAliases ) => {
    const result = [ ...DEFAULT_LANGUAGES ];

    const languages = new Set();
    fromLabels.forEach( langCode => languages.add( langCode ) );
    fromDescriptions.forEach( langCode => languages.add( langCode ) );
    fromAliases.forEach( langCode => languages.add( langCode ) );

    // remove DEFAULT_LANGUAGES from set
    result.forEach( langCode => languages.delete( langCode ) );
    const sorted = Array.from( languages );
github envkey / envkey-app / envkey-react / src / lib / env / query.js View on Github external
R.flatten,
    R.uniq,
    R.sort(R.ascend(R.identity))
  )),

  allEntries = defaultMemoize(R.pipe(
    // R.filter(R.complement(R.prop("@@__hidden__"))),
    allKeys,
    R.filter(k => k.indexOf("@@__") != 0)
  )),

  subEnvEntries = (envsWithMeta, subEnvId)=> allEntries({
    [subEnvId]: findSubEnv(subEnvId, envsWithMeta)
  }),

  allSubEnvsSorted = defaultMemoize(R.pipe(
    R.values,
    R.map(R.pipe(
      R.propOr({},"@@__sub__"),
      R.keys
    )),
    R.flatten,
    R.uniq,
    R.sort(R.ascend(R.identity))
  )),

  allEntriesWithSubEnvs = defaultMemoize(envsWithMeta => {
    return R.pipe(
      allSubEnvsSorted,
      R.pipe(
        R.map(subEnvId => (findSubEnv(subEnvId, envsWithMeta))),
        allEntries
github neos / neos-ui / packages / neos-ui-redux-store / src / CR / NodeTypes / index.js View on Github external
constraints: Immutable.fromJS($get('cr.nodeTypes.constraints', state)),
            inheritanceMap: Immutable.fromJS($get('cr.nodeTypes.inheritanceMap', state)),
            groups: Immutable.fromJS($get('cr.nodeTypes.groups', state))
        })
    )
});

//
// selectors
//

const byNameSelector = state => name => $get(['cr', 'nodeTypes', 'byName', name], state);

const subTypesSelector = name => $get(['cr', 'nodeTypes', 'inheritanceMap', 'subTypes', name]);

const isOfTypeSelector = defaultMemoize(
    superTypeName => subTypeName => createSelector(
        [
            subTypesSelector(superTypeName)
        ],
        subTypes => subTypes.indexOf(subTypeName) !== -1
    )
);

//
// Export the selectors
//
export const selectors = {
    byNameSelector,
    subTypesSelector,
    isOfTypeSelector
};
github vlsergey / WE-Framework / src / core / selectors.js View on Github external
const languages = new Set();
    fromLabels.forEach( langCode => languages.add( langCode ) );
    fromDescriptions.forEach( langCode => languages.add( langCode ) );
    fromAliases.forEach( langCode => languages.add( langCode ) );

    // remove DEFAULT_LANGUAGES from set
    result.forEach( langCode => languages.delete( langCode ) );
    const sorted = Array.from( languages );
    sorted.sort();

    sorted.forEach( langCode => result.push( langCode ) );
    return result;
  } );

export const labelFromEntityByLanguage = defaultMemoize( ( entity, language ) => {
  const allLanguages = labelsFromEntity( entity ) || EMPTY_OBJECT;
  return allLanguages[ language ] || EMPTY_OBJECT;
} );
export const labelValue = labelObject => ( labelObject || EMPTY_OBJECT ).value || EMPTY_STRING;

export const descriptionFromEntityByLanguage = defaultMemoize( ( entity, language ) => {
  const allLanguages = descriptionsFromEntity( entity ) || EMPTY_OBJECT;
  return allLanguages[ language ] || EMPTY_OBJECT;
} );
export const descriptionValue = labelObject => ( labelObject || EMPTY_OBJECT ).value || EMPTY_STRING;

export const aliasesFromEntityByLanguage = defaultMemoize( ( entity, language ) => {
  const allLanguages = aliasesFromEntity( entity ) || EMPTY_OBJECT;
  return allLanguages[ language ] || EMPTY_ARRAY;
} );
export const aliasValues = createSelector(