How to use redux-query - 10 common examples

To help you get started, we’ve selected a few redux-query 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 isaacplmann / ngrx-query / lib / services / effects.service.js View on Github external
.mergeMap(function (action) {
            var url = action.url, _a = action.transform, transform = _a === void 0 ? identity : _a, update = action.update, body = action.body, optimisticUpdate = action.optimisticUpdate, _b = action.options, options = _b === void 0 ? {} : _b;
            invariant(!!url, 'Missing required `url` field in action handler');
            var state = getLatest(_this.store);
            var entities = _this.config && _this.config.entitiesSelector && _this.config.entitiesSelector(state)
                || defaultEntitiesSelector(state);
            var optimisticEntities;
            if (optimisticUpdate) {
                optimisticEntities = optimisticUpdateEntities(optimisticUpdate, entities);
            }
            var queryKey = reconcileQueryKey(action);
            // const start = new Date();
            var _c = options.method, method = _c === void 0 ? httpMethods.POST : _c;
            var request = {
                url: url,
                method: method,
                body: body,
                headers: options.headers,
                withCredentials: options.credentials === 'include',
            };
            // Note: only the entities that are included in `optimisticUpdate` will be passed along in the
            // `mutateStart` action as `optimisticEntities`
            _this.store.dispatch(actions.mutateStart(url, body, request, optimisticEntities, queryKey));
            return _this.http.request(url, request)
                .map(function (response) {
                if (!response.ok) {
                    throw response;
github amplitude / redux-query / packages / redux-query-react / src / hooks / use-request.js View on Github external
return () => {
      // If there is an pending request whenever the component unmounts of the query config
      // changes, cancel the pending request.
      if (isPendingRef.current) {
        const queryKey = getQueryKey(queryConfig);

        if (queryKey) {
          dispatchCancelToRedux(queryKey);
        }
      }
    };
  }, [dispatchCancelToRedux, dispatchRequestToRedux, queryConfig]);
github redradix / redux-base-app / src / components / context / my-account / user-form-context.js View on Github external
}

const mapDispatchToProps = { storeUser, createUser, updateUser }

const mapPropsToQuery = function(props) {
  if (props.initialValues) return
  return {
    url: `/api/users/${props.id}`,
    transform: props.storeUser,
    update: {} // Disregard redux-query update methods
  }
}

const enhance = compose(
  connect(mapStateToProps, mapDispatchToProps),
  connectRequest(mapPropsToQuery)
)

UserFormContext = enhance(UserFormContext)

export default UserFormContext
github redradix / redux-base-app / src / components / context / my-account / users-list-context.js View on Github external
users: getUserListPage(state, currentPage),
    isReady: isUserListReady(state)
  }
}

const mapDispatchToProps = { storeUsers, setPageNumber }

const mapPropsToQuery = (props) => ({
  url: `/api/user/list?page=${props.currentPage}`,
  transform: props.storeUsers,
  update: {} // Disregard redux-query update methods
})

const enhance = compose(
  connect(mapStateToProps, mapDispatchToProps),
  connectRequest(mapPropsToQuery)
)

UsersListContext = enhance(UsersListContext)

export default UsersListContext
github redradix / redux-base-app / src / services / users / actions.js View on Github external
export const deleteUser = (id, callback) => (dispatch, getState) => dispatch(
  mutateAsync({
    url: `${ENDPOINT}${id}`,
    options: { method: 'DELETE' }
  })
)
.then(function() {
  // NOTE: When server responds with 204 (no content), redux-query will not
  // call either of the callback functions, transform and update
  dispatch(remove(DOMAIN, id))
  dispatch(setTotal(DOMAIN, getTotal(getState(), DOMAIN) - 1))
  dispatch(clearFromPageOnwards(DOMAIN, getPageNumber(getState(), DOMAIN)))
  callback()
})
github amplitude / redux-query / examples / async / store / configureStore.js View on Github external
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import rootReducer from '../reducers'
import { queryMiddleware } from 'redux-query'

const createStoreWithMiddleware = applyMiddleware(
  thunkMiddleware,
  queryMiddleware((state) => state.queries, (state) => state.entities),
  createLogger()
)(createStore)

export default function configureStore(initialState) {
  const store = createStoreWithMiddleware(rootReducer, initialState)

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers')
      store.replaceReducer(nextRootReducer)
    })
  }

  return store
}
github amplitude / redux-query / examples / async / src / store / configureStore.js View on Github external
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import rootReducer from '../reducers';
import { queryMiddleware } from 'redux-query';

const createStoreWithMiddleware = applyMiddleware(
  thunkMiddleware,
  queryMiddleware(state => state.queries, state => state.entities),
  createLogger(),
)(createStore);

export default function configureStore(initialState) {
  const store = createStoreWithMiddleware(rootReducer, initialState);

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers');
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}
github amplitude / redux-query / packages / redux-query-react / src / hooks / use-request.js View on Github external
const dispatchRequestToRedux = useConstCallback(queryConfig => {
    const promise = reduxDispatch(requestAsync(queryConfig));

    // If a promise is not returned, we know that the query middleware ignored this request and
    // one will not be made, so don't consider it as "pending".
    if (promise) {
      isPendingRef.current = true;
    }

    return promise;
  });
github isaacplmann / ngrx-query / lib / services / effects.service.js View on Github external
.map(function (action) {
            var url = action.url, force = action.force, retry = action.retry, update = action.update;
            invariant(!!url, 'Missing required `url` field in action handler');
            invariant(!!update, 'Missing required `update` field in action handler');
            var queryKey = reconcileQueryKey(action);
            var state = getLatest(_this.store);
            var queries = _this.config && _this.config.queriesSelector && _this.config.queriesSelector(state)
                || defaultQueriesSelector(state);
            var queriesState = queries[queryKey];
            var _a = queriesState || {}, isPending = _a.isPending, status = _a.status;
            var hasSucceeded = status >= 200 && status < 300;
            var attemptRequest = force || !queriesState || (retry !== false && !isPending && !hasSucceeded);
            return { attemptRequest: attemptRequest, action: action };
        })
            .filter(function (_a) {
github amplitude / redux-query / packages / redux-query-react / src / hooks / use-memoized-query-config.js View on Github external
const useMemoizedQueryConfig = (
  providedQueryConfig: ?QueryConfig,
  transform: (?QueryConfig) => ?QueryConfig = identity,
): ?QueryConfig => {
  const [queryConfig, setQueryConfig] = React.useState(
    providedQueryConfig ? transform(providedQueryConfig) : null,
  );
  const previousQueryKey = React.useRef(getQueryKey(providedQueryConfig));

  React.useEffect(() => {
    const queryKey = getQueryKey(providedQueryConfig);

    if (queryKey !== previousQueryKey.current) {
      previousQueryKey.current = queryKey;
      setQueryConfig(providedQueryConfig ? transform(providedQueryConfig) : null);
    }
  }, [providedQueryConfig, transform]);

  return queryConfig;
};