How to use react-apollo - 10 common examples

To help you get started, we’ve selected a few react-apollo 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 OriginProtocol / origin / dapps / marketplace / src / pages / identity / TelegramAttestation.js View on Github external
const TelegramVerifyAttestation = ({
  identity,
  onComplete,
  onError,
  isMobile
}) => {
  const [loadStatus, { data, error }] = useLazyQuery(CheckTelegramStatusQuery, {
    variables: {
      identity,
      maxTries: 30
    },
    notifyOnNetworkStatusChange: true,
    fetchPolicy: 'network-only'
  })

  useEffect(() => {
    if (!isMobile) {
      loadStatus()
      return
    }

    // Note: Starting the poll after a few seconds of delay
    // This is because, on mobile, the query gets terminated when
github rsnay / wadayano / client / src / components / student / QuizTaker.js View on Github external
const QuizTaker = () => {
  const { quizId } = useParams();
  const history = useHistory();

  // Yes, this is a lot of state...
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [phase, setPhase] = useState(phases.CONCEPTS);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [currentQuestionCompleted, setCurrentQuestionCompleted] = useState(false);
  const [quiz, setQuiz] = useState(null);
  const [randomizedQuestions, setRandomizedQuestions] = useState(null);
  const [quizAttempt, setQuizAttempt] = useState(null);
  const [isCompleted, setIsCompleted] = useState(false);

  const [startMutation] = useMutation(START_MUTATION);
  const [completeMutation] = useMutation(COMPLETE_MUTATION);

  // Sends the completeQuiz mutation and displays if grade postback was successful or not (if applicable)
  const completeQuiz = async quizAttemptId => {
    setIsLoading(true);
    try {
      // Pass the quiz attempt ID to be completed
      const result = await completeMutation({ variables: { quizAttemptId } });
      console.log(result);

      // A QuizGradePayload contains isGraded (bool!), postSucceeded (bool), error (string), and quizAttempt (quizAttempt!)
      const quizGradePayload = result.data.completeQuizAttempt;

      // If it was graded, check if the LTI grade passback was successful or not
      if (quizGradePayload.isGraded && quizGradePayload.postSucceeded) {
        ButterToast.raise({
github cosmicjs / react-graphql-static-site / src / graphql / index.js View on Github external
import { ApolloClient, createNetworkInterface, } from "react-apollo";

// ------------------------------

const networkInterface = createNetworkInterface({
	uri: "https://graphql.cosmicjs.com/v1",
});

networkInterface.use([
	{
		applyMiddleware(req, next) {
			console.log({ req, });

			next();
		},
	},
]);

const client = new ApolloClient({
	networkInterface: networkInterface,
});
github benawad / hello-world-nextjs / apollo / initApollo.js View on Github external
export default function initApollo(headers, initialState = {}) {
  // Make sure to create a new client for every server-side request so that data
  // isn't shared between connections (which would be bad)
  if (!process.browser) {
    return create(headers, initialState);
  }

  // Reuse client on the client-side
  if (!apolloClient) {
    const wsClient = new SubscriptionClient(subscriptionUri, {
      reconnect: true
    });
    const networkInterface = createNetworkInterface({
      uri
    });

    networkInterface.use([{
      applyMiddleware(req, next) {
        if (!req.options.headers) {
          req.options.headers = {};
        }
        console.log('middleware called! 2');
        // if (apolloClient) {
        //   req.options.headers['x-token'] = localStorage.getItem('token');
        //   req.options.headers['x-refresh-token'] = localStorage.getItem('refreshToken');
        // }

        next();
      }
github alidcastano / rogue.js / packages / hocs / apollo / index.js View on Github external
async function initCache (ctx, App, client) {
  try {
    const AppWithApollo = h(ApolloProvider, { client }, h(App))
    await getDataFromTree(
      ctx.app.routable(AppWithApollo)
    )
  } 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)
  }
}
github alidcastano / rogue.js / packages / rogue-hocs / apollo / index.js View on Github external
async function initCache (ctx, App, client) {
  try {
    const AppWithApollo = h(ApolloProvider, { client }, h(App))
    await getDataFromTree(
      ctx.app.routable(AppWithApollo)
    )
  } 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)
  }
}
github strues / boldr / project / src / serverEntry.js View on Github external
const sheet = new ServerStyleSheet();

    const location = req.url;
    // appComponent takes the apolloClient, the reduxStore, location (req.url), the routerContext and
    // the  component.
    // It populates the ApolloProvider, StaticRouter and places the application component
    const appComponent = serverRender(
      { apolloClient, reduxStore, location, routerContext },
      ,
    );
    let markup = '';
    try {
      // render the applicaation to a string, collecting what's necessary to populate apollo's data and let styled-components
      // create stylesheet elements
      markup = await renderToStringWithData(sheet.collectStyles(appComponent));
    } catch (err) {
      console.error('Unable to render server side React:', err);
    }

    const chunkNames = flushChunkNames();
    console.log('[BOLDR] Flushing chunks...', chunkNames);

    const { scripts, stylesheets, cssHashRaw } = flushChunks(clientStats, {
      chunkNames: chunkNames,
      before: ['bootstrap', 'vendor'],
      after: ['main'],
      outputPath,
    });

    const finalState = {
      ...reduxStore.getState(),
github okgrow / advanced-graphql / ui / src / server.js View on Github external
}),
      cache,
    });

    // to be used by react-apollo
    const component = (
      
        
          
            
          
        
      
    );

    const content = await renderToStringWithData(component);

    const state = cache.extract();

    const styleTags = sheet.getStyleElement();

    const html = ;

    res.status(200);
    res.send(`\n${ReactDOM.renderToStaticMarkup(html)}`);
  } catch (e) {
    console.log(e);

    const component = (
      
        
          Server-side rendering error... Check the logs!
github VulcanJS / Vulcan / packages / vulcan-lib / lib / server / apollo-ssr / ssrMiddleware.js View on Github external
// this avoids caching server side
  const client = createClient(req);
  // TODO adapt to Vulcan
  const context = {};

  const App = appGenerator({ req, client, context })

  // Alternative that relies on Meteor server-render:
  // @see https://github.com/szomolanyi/MeteorApolloStarter/blob/master/imports/startup/server/ssr.js

  // TODO: adapt to Vulcan
  // @see https://github.com/apollographql/GitHunt-React/blob/master/src/server.js
  // @see https://www.apollographql.com/docs/react/features/server-side-rendering.html#renderToStringWithData
  // equivalent to calling getDataFromTree and then renderToStringWithData
  //sink.appendToBody(ReactDOM.renderToStaticMarkup(<div id="react-app"></div>))
  const content = await renderToStringWithData(App)
  console.log(content.slice(0,100))
  const wrappedContent = `<div id="react-app">${content}</div>`
  sink.appendToBody(wrappedContent)
  //sink.renderIntoElementById('react-app', 'HI')//content)
  // add headers
  const head = ReactDOM.renderToString(Head)
  sink.appendToHead(head)
  // add data
  const initialState = client.extract();
  sink.appendToBody(ReactDOM.renderToString(
github VulcanJS / Vulcan / packages / vulcan-lib / lib / server / apollo-ssr / renderPage.js View on Github external
// middlewares at this point
    // @see https://github.com/meteor/meteor-feature-requests/issues/174#issuecomment-441047495

    const App = ;

    // run user registered callbacks that wraps the React app
    const WrappedApp = runCallbacks({
      name: 'router.server.wrapper',
      iterator: App,
      properties: { req, context, apolloClient: client },
    });

    // equivalent to calling getDataFromTree and then renderToStringWithData
    let htmlContent = '';
    try {
    htmlContent = await renderToStringWithData(WrappedApp);
    } catch (err) {
      console.error(`Error while server-rendering. date: ${new Date().toString()} url: ${req.url}`); // eslint-disable-line no-console
      console.error(err);
      // show error in client in dev
      if (Meteor.isDevelopment) {
        htmlContent = `Error while server-rendering: ${err.message}`;
      }
    }

    // TODO: there should be a cleaner way to set this wrapper
    // id must always match the client side start.jsx file
    const wrappedHtmlContent = `<div id="react-app">${htmlContent}</div>`;
    sink.appendToBody(wrappedHtmlContent);
    // TODO: this sounds cleaner but where do we add the <div id="react-app"> ?
    //sink.renderIntoElementById('react-app', content)
</div>