How to use next - 10 common examples

To help you get started, we’ve selected a few next 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 flow-typed / flow-typed / definitions / npm / next_v2.x.x / test_next_v2.x.x.js View on Github external
// $ExpectError
InvalidNumLink;

// $ExpectError
 {}}>Prefetch;

// $ExpectError
Router.onRouteChangeStart = {};

Router.onRouteChangeStart = (url: string) => {};
Router.onRouteChangeStart = null;

Router.onRouteChangeComplete = (url: string) => {};
Router.onRouteChangeComplete = null;

Router.onRouteChangeError = (err, url) => {
  if (err.cancelled) {
    console.log(`Route to ${url} was cancelled!`)
  }
}

Router.push('/about');
Router.push('/about', '/');
Router.replace('/about');
Router.replace('/about', '/');

const r: string = Router.route;
const p: string = Router.pathname;
const q: {} = Router.query;

export default class TestDocument extends Document {
  static async getInitialProps (ctx: Context) {
github luckcoding / hotchcms / front / pages / _app.js View on Github external
import React from 'react'
import App, { Container } from 'next/app'
import NProgress from 'nprogress'
import Router from 'next/router'
import qs from 'qs'
import { Provider } from 'react-redux'
import withRedux from 'next-redux-wrapper'
import withReduxSaga from 'next-redux-saga'
import { I18nProvider } from 'helpers/I18n'
import configureStore from 'store/configureStore'

Router.events.on('routeChangeStart', (url) => {
  console.log(`Loading: ${url}`)
  NProgress.start()
})
Router.events.on('routeChangeComplete', () => NProgress.done())
Router.events.on('routeChangeError', () => NProgress.done())

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    try {
      // search params
      const search = qs.parse(ctx.asPath.split('?')[1] || '')

      let pageInitialProps = {}

      if (Component.getInitialProps) {
        pageInitialProps = await Component.getInitialProps({ ...ctx, search })
      }

      // Get the `locale` from the request object on the server.
      // In the browser, use the same values that the server serialized.
github zprima / jwt-cors-app / app / utils / auth.js View on Github external
try {
    const response = await axios.get(serverUrl + "/api/token/ping", { headers: { 'Authorization': token } });
    // dont really care about response, as long as it not an error
    console.log("token ping:", response.data.msg)
  } catch (err) {
    // in case of error
    console.log(err.response.data.msg);
    console.log("redirecting back to main page");
    // redirect to login
    if (ctx.res) {
      ctx.res.writeHead(302, {
        Location: '/'
      })
      ctx.res.end()
    } else {
      Router.push('/')
    }
  }
}
github devinit / datahub / packages / app / src / components / templates / CountryProfile / index.tsx View on Github external
import Router from 'next/router';
import Link from 'next/link';
import Generic from '../Generic';

// TODO: the dynamic types are a pain to work with, need to get improved submit PR
const dynamicOpts: DynamicOptions = {
  ssr: true,
  loading: () =&gt; <p>Loading...</p>,
    modules: props =&gt; ({
        CountryProfileLowerTabs: import('../../organisms/CountryProfileLowerTabs') as Promise
      }),
    render: (props, {CountryProfileLowerTabs}) =&gt;
        
};

const DynamicCountryProfileLowerTabs = dynamic(dynamicOpts as any);

interface Props  {
  id: string;
  rehydrated?: boolean;
  state?: StateToShare;
}

export default class Profile extends React.Component {
  public static init(props) {
    const country = getCountry(props.id);
    const selectedTab = props.state &amp;&amp; props.state.chartId &amp;&amp;
      props.state.chartId !== GOVERNMENT_FINANCE_LOWER ? 1 : 0;
    return {selectedTab, country};
  }
  public state: {
    selectedTab: number,
github statico / aspen / pages / index.js View on Github external
this.setState({ results: null })
      return
    }

    try {
      this.setState({ inProgress: true, results: null })

      const queryString = qs.stringify({
        query,
        page: page &amp;&amp; page &gt; 0 ? page + 1 : undefined,
        sloppy: sloppy ? 1 : undefined
      })

      // If we're typing fast, don't add incomplete queries to browser history.
      if (this.inFlightRequest) {
        Router.replace('/?' + queryString)
      } else {
        Router.push('/?' + queryString)
      }

      if (this.inFlightRequest) this.inFlightRequest.abort()
      const req = this.inFlightRequest = request.get(getOrigin() + '/search').query(queryString).withCredentials()
      const response = await req
      const obj = response.body

      if (obj.error) {
        // Elasticsearch will complain about broken queries, like '"foo' (missing a double quote)
        if (/QueryParsingException/.test(obj.error)) {
          obj.error = <span>
            That search query looks incomplete. Please see the {' '}
            <a href="https://www.elastic.co/guide/en/elasticsearch/reference/1.7/query-dsl-query-string-query.html#query-string-syntax">Elasticsearch 1.7 query string documentation</a>.
          </span>
github lfades / next-with-apollo / src / withApollo.tsx View on Github external
apolloState={apolloState}
                apollo={apollo}
              />
            );
          } catch (error) {
            // Prevent Apollo Client GraphQL errors from crashing SSR.
            if (process.env.NODE_ENV !== 'production') {
              // tslint:disable-next-line no-console This is a necessary debugging log
              console.error('GraphQL error occurred [getDataFromTree]', error);
            }
          }

          if (ssrMode) {
            // getDataFromTree does not call componentWillUnmount
            // head side effect therefore need to be cleared manually
            Head.rewind();
          }

          apolloState.data = apollo.cache.extract();
        }

        // To avoid calling initApollo() twice in the server we send the Apollo Client as a prop
        // to the component, otherwise the component would have to call initApollo() again but this
        // time without the context, once that happens the following code will make sure we send
        // the prop as `null` to the browser
        (apollo as any).toJSON = () => {
          return null;
        };

        return {
          ...appProps,
          apolloState,
github orbiting / publikator-frontend / lib / apollo / withApolloClient.js View on Github external
{...appProps}
              apolloClient={apollo}
              headers={headers}
              serverContext={ctx}
            />
          )
        } catch (error) {
          // Prevent Apollo Client GraphQL errors from crashing SSR.
          // Handle them in components via the data.error prop:
          // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
          console.error('Error while running `getDataFromTree`', error)
        }

        // getDataFromTree does not call componentWillUnmount
        // head side effect therefore need to be cleared manually
        Head.rewind()

        // Extract query data from the Apollo store
        apolloState = apollo.cache.extract()
      }

      return {
        ...appProps,
        apolloState,
        headers
      }
    }
github artsmia / lume / app / apollo / index.js View on Github external
router={router}
              apolloState={apolloState}
              apolloClient={apollo}
            />
          )
        } catch (error) {
          // Prevent Apollo Client GraphQL errors from crashing SSR.
          // Handle them in components via the data.error prop:
          // http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error
          console.error('Error while running `getDataFromTree`', error)
        }

        if (!process.browser) {
          // getDataFromTree does not call componentWillUnmount
          // head side effect therefore need to be cleared manually
          Head.rewind()
        }

        // Extract query data from the Apollo store
        apolloState.data = apollo.cache.extract()

        return {
          ...appProps,
          apolloState
        }
      } catch (ex) {
        console.error(ex)
      }
    }
github maapteh / graphql-modules-app / packages / app / src / graphql / apollo.js View on Github external
}}
                            />,
                        );
                    } catch (error) {
                        // Prevent Apollo Client GraphQL errors from crashing SSR.
                        // Handle them in components via the data.error prop:
                        // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
                        console.error(
                            'Error while running `getDataFromTree`',
                            error,
                        );
                    }

                    // getDataFromTree does not call componentWillUnmount
                    // head side effect therefore need to be cleared manually
                    Head.rewind();
                }
            }

            // Extract query data from the Apollo store
            const apolloState = ctx.apolloClient.cache.extract();

            return {
                ...pageProps,
                apolloState,
                ssrComplete: true,
            };
        };
    }
github jaydenseric / apollo-upload-examples / app / pages / _app.js View on Github external
try {
      const { getDataFromTree } = await import('@apollo/react-ssr')
      await getDataFromTree(
        
      )
    } catch (error) {
      // Prevent crash from GraphQL errors.
      console.error(error)
    }

    Head.rewind()

    props.apolloCache = apolloClient.cache.extract()
  }

  return props
}