How to use query-string - 10 common examples

To help you get started, we’ve selected a few query-string 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 SolidZORO / leaa / packages / leaa-dashboard / src / components / ErrorBoundary / ErrorBoundary.tsx View on Github external
componentDidCatch(error: Error, info: {}) {
    // TIPS: Many times DidCatch is because the JS file can't be retrieved, so refresh it first.
    const qs = queryString.parse(window.location.search);

    if (!qs[CATCH_HAS_REFRESH_URL_PARAM]) {
      window.location.href = urlUtil.mergeParamToUrlQuery({
        window,
        params: { [CATCH_HAS_REFRESH_URL_PARAM]: 1 },
        replace: false,
      });
    }

    console.log('---- ALL-STACK ----', info, error);

    this.setState({ errorInfo: error.message });
  }
github focallocal / fl-maps / imports / client / ui / app.js View on Github external
function changeHistory({ pathname = null, params, push }) {
  const p = Object.assign(params);
  Object.keys(p).forEach(key => p[key] === undefined && delete p[key]);
  const s = qs.parse(window.location.search);
  Object.assign(s, p);
  Object.keys(s).forEach(key => s[key] === null && delete s[key]);
  const search = qs.stringify(s);
  //############################################################################
  // TERRIBLE WORKAROUND FOR ISSUE https://github.com/focallocal/fl-maps/issues/742
  if (pathname && pathname !== location.pathname) {
    console.log("##########", pathname + "?" + search);
    location.href = pathname + "?" + search;
    return;
  }
  //############################################################################
  pathname = pathname || window.location.pathname;
  if (push) {
    history.push({ pathname, search });
  } else {
    history.replace({ pathname, search });
  }
}
github fidalgodev / movie-library-react / src / containers / Search.js View on Github external
const Search = ({
  geral,
  match,
  location,
  getMoviesSearch,
  clearMovies,
  movies,
}) => {
  const { query } = match.params;
  const params = queryString.parse(location.search);
  const { secure_base_url } = geral.base.images;

  // Fetch movies hook
  useFetchMoviesSearch(query, getMoviesSearch, params, clearMovies);

  // If loading
  if (movies.loading) {
    return ;
  }

  //If there are no results
  else if (movies.total_results === 0) {
    return (
github fastai / course-v3 / fastai-video-browser / src / App.jsx View on Github external
static getDerivedStateFromProps(props, state) {
    const parsed = qs.parse(window.location.search)
    // Parse selected lesson from query string, so we don't have to deal with real /routing.
    return { 
      ...state, 
      selectedLesson: parseInt(parsed.lesson) || 1,
      startAt: parseInt(parsed.t, 10) 
    }
  }
github stellar / js-stellar-wallets / src / transfers / WithdrawProvider.ts View on Github external
public async startWithdraw(
    params: WithdrawRequest,
  ): Promise {
    const request = { ...params, account: this.account };
    const isAuthRequired = this.getAuthStatus("withdraw", params.asset_code);
    const qs = queryString.stringify(request);

    const response = await fetch(`${this.transferServer}/withdraw?${qs}`, {
      headers: isAuthRequired ? this.getHeaders() : undefined,
    });
    const json = (await response.json()) as TransferResponse;

    if (json.error) {
      const error: TransferError = new Error(json.error);
      error.originalResponse = json;
      throw error;
    }

    // if this was an auth-required token, insert the JWT
    if (
      isAuthRequired &&
      json.type === TransferResponseType.interactive_customer_info_needed &&
github WebbyLab / itsquiz-wall / shared / api / ApiClient.js View on Github external
request({ url, method, params = {}, body }) {
        if (this.authToken) {
            /* eslint-disable */
            params.token = this.authToken;
            /* eslint-enable */
        }

        const urlWithQuery = `${url}?${queryString.stringify(params)}`;

        const init = {
            method,
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            }
        };

        if (method !== 'get' && method !== 'head') {
            init.body = JSON.stringify(body);
        }

        return fetch(`${this.prefix}/${urlWithQuery}`, init).then(res => {
            if (res.status >= 400) {
                throw new Error('Bad response from server');
github DivanteLtd / vue-storefront / core / server-entry.ts View on Github external
export default async context => {
  let storeCode = context.vs.storeCode
  if (config.storeViews.multistore === true) {
    if (!storeCode) { // this is from url
      const currentRoute = Object.assign({ path: queryString.parseUrl(context.url).url/* this gets just the url path part */, host: context.server.request.headers.host })
      storeCode = storeCodeFromRoute(currentRoute)
    }
  }
  const { app, router, store, initialState } = await createApp(context, context.vs && context.vs.config ? context.vs.config : buildTimeConfig, storeCode)

  RouterManager.flushRouteQueue(router)
  context.initialState = initialState
  return new Promise((resolve, reject) => {
    context.output.cacheTags = new Set()
    const meta = (app as any).$meta()
    router.push(context.url)
    context.meta = meta
    router.onReady(() => {
      const matchedComponents = router.getMatchedComponents()
      if (!matchedComponents.length || !matchedComponents[0]) {
        return reject(new HttpError('No components matched', 404)) // TODO - don't redirect if already on page-not-found
github OfficeDev / script-lab / packages / editor / src / index.tsx View on Github external
function getReactElementBasedOnQueryParams() {
  const params: { state?: string; code?: string } = queryString.parse(
    queryString.extract(window.location.href),
  );

  // For the GitHub auth callback, we've registered the root page.
  // To avoid needing to change it at the GitHub layer (and thus breaking it across
  // our redirected environments), it's best to stick with what the registration
  // already expects.  And so, if we see "state" and "code" on the URL --
  // which is a telltale sign of GitHub redirecting after successful auth --
  // got ahead and render the AuthPage component.
  if (params.state && params.code) {
    return ;
  } else {
    // Add a keyboard listener to [try to] intercept "ctrl+save", since we auto-save anyway
    // and since the browser/host "save as" dialog would be unwanted here
    document.addEventListener(
      'keydown',
      e => {
github gojek / mlp / ui / packages / lib / src / hooks / useApi.js View on Github external
options => {
      let didCancel = false;

      const apiOptions = !!options
        ? {
            ...args.options,
            ...options
          }
        : args.options;

      dispatch({ type: "FETCH_INIT" });
      (apiOptions.useMockData && apiOptions.mock
        ? fetchMockData(apiOptions.mock, apiOptions)
        : fetchJson(
            queryString.stringifyUrl({
              url: urlJoin(apiOptions.baseApiUrl, endpoint),
              // query params supplied via `apiOptions` have a higher priority
              // and will override query param with the same name if it is
              // present in the `endpoint`
              query: apiOptions.query
            }),
            args.authCtx,
            apiOptions
          )
      )
        .then(result => {
          if (!didCancel)
            dispatch({
              type: "FETCH_SUCCESS",
              payload: result.body,
              headers: result.headers
github choerodon / manager-service / react / src / app / iam / containers / global / api-test / APIDetail.js View on Github external
componentWillMount() {
    if (APITestStore.getApiDetail.description === '[]') {
      const { controller, version, service, operationId } = this.state;
      const queryObj = {
        version,
        operation_id: operationId,
      };
      defaultAxios.get(`${urlPrefix}/manager/v1/swaggers/${service}/controllers/${controller}/paths?${querystring.stringify(queryObj)}`).then((data) => {
        data.paths.some((item) => {
          if (item.operationId === operationId) {
            const { basePath, url } = item;
            APITestStore.setApiDetail(item);
            this.setState({
              loading: false,
              requestUrl: `${urlPrefix}${basePath}${url}`,
            });
            return true;
          }
          return false;
        });
      });
    } else {
      const { basePath, url } = APITestStore.getApiDetail;
      this.setState({

query-string

Parse and stringify URL query strings

MIT
Latest version published 3 months ago

Package Health Score

84 / 100
Full package analysis