#ApolloClient
Explore tagged Tumblr posts
asadmukhtarr · 3 months ago
Text
In modern web development, efficient data fetching is crucial for providing a smooth and responsive user experience. Traditional REST APIs can sometimes lead to over-fetching or under-fetching of data, causing unnecessary network calls or missing critical information. GraphQL, an API query language developed by Facebook, solves this problem by allowing clients to request exactly the data they need. In this guide, we’ll walk you through the steps of integrating Angular 19 with GraphQL for efficient data fetching, making your application more performant and responsive.
0 notes
technsavi · 2 years ago
Text
Use of fetchMore UseQuery in nextJs
Here is an implementation of using the Pagination of Apollo Client in a convenient way. The fetchMore function of ApolloClient provides us an option to request the data with updated query parameters and to merge the results of the previous and latest responses. About fetchMore function – Pagination always involves sending follow-up queries to your GraphQL server to obtain additional pages of…
Tumblr media
View On WordPress
0 notes
laravelvuejs · 4 years ago
Text
Apollo 图片上传,下载实战课程
 Buy Now   Price: US$24.99 作为Vuejs + Apollo GraphQL + MongoDB GridFS 综合运用实战课程,内容聚焦于全面介绍如何运用最新的Vuejs,GraphQL,Apollo Server等web技术以及MongoDB GridFS 大文件存储方案构建实现图形文件的上传,下载的APP,从APP创建到发布,对关键部分例如 ApolloClient 和 ApolloServer的创建,配置进行详细讲解,让学习者体会 Apollo 和 GraphQL 的强大功能,确确实实掌握干货web开发技术
Tumblr media
View On WordPress
0 notes
alpaca1 · 5 years ago
Text
Webプログラマってどんな技術が必要?
1: 以下、5ちゃんねるからVIPがお送りします 2020/08/24(月) 22:12:55.844 ID:dz6g7NL60 勉強した事実践した事羅列するから 俺がここからやるべき事 知るべき事教えてくれ
フロントエンドは TypeScript React Redux ApolloClient 辺りは趣味サービスで使った
やってみたい技術は MobX、Recoil、RxJS
バックエンドは Flask(CRUD実装した程度) Express.js JWTとBCrypt使った認証機能 (実戦で使ってない)
NoSQLとしてMongoDB RDBMSとしてPostgresql テーブル設計なんかは無理だけどSQL書いて目的のデータを得るくらいならできる
蛇足としてCも若干齧ってCLIとSQLite使った簡単なアプリくらいなら作れる
続き…
View On WordPress
0 notes
t-baba · 6 years ago
Photo
Tumblr media
How to Build a Web App with GraphQL and React
In this tutorial, we'll learn to build a web application with React and GraphQL. We'll consume an API available from graphql-pokemon and serve it from this link, which allows you to get information about Pokémon.
GraphQL is a query language for APIs and a runtime for fulfilling those queries created by Facebook. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
In this tutorial, we'll only learn the front end of a GraphQL application that makes use of Apollo for fetching data from a ready GraphQL API hosted on the web.
Let's get started with the prerequisites!
Prerequisites
There are a few prerequisites for this tutorial:
recent versions of Node.js and npm installed on your system
knowledge of JavaScript/ES6
familiarity with React
If you don't have Node and npm installed on your development machine, you can simply download the binaries for your system from the official website. You can also use NVM, a POSIX-compliant bash script to manage multiple active Node.js versions.
Installing create-react-app
Let's install the create-react-app tool that allows you to quickly initialize and work with React projects.
Open a new terminal and run the following command:
npm install -g create-react-app
Note: You may need to use sudo before your command in Linux and macOS or use a command prompt with administrator rights if you get EACCESS errors when installing the package globally on your machine. You can also simply fix your npm permissions.
At the time of writing, this installs create-react-app v3.1.1.
Creating a React Project
Now we're ready to create our React project.
Go back to your terminal and run the following command:
create-react-app react-pokemon
Next, navigate into your project's folder and start the local development server:
cd react-pokemon npm start
Go to http://localhost:3000 in your web browser to see your app up and running.
This is a screenshot of the app at this point:
Installing Apollo Client
Apollo Client is a complete data management solution that's commonly used with React, but can be used with any other library or framework.
Apollo provides intelligent caching that enables it to be a single source of truth for the local and remote data in your application.
You'll need to install the following packages in your React project to work with Apollo:
graphql: the JavaScript reference implementation for GraphQL
apollo-client: a fully-featured caching GraphQL client with integrations for React, Angular, and more
apollo-cache-inmemory: the recommended cache implementation for Apollo Client 2.0
apollo-link-http: the most common Apollo Link, a system of modular components for GraphQL networking
react-apollo: this package allows you to fetch data from your GraphQL server and use it in building complex and reactive UIs using the React framework
graphql-tag: this package provides helpful utilities for parsing GraphQL queries such as gql tag.
Open a new terminal and navigate to your project's folder, then run the following commands:
npm install graphql --save npm install apollo-client --save npm install apollo-cache-inmemory --save npm install apollo-link-http --save npm install react-apollo --save npm install graphql-tag --save
Now that we've installed the necessary packages, we need to create an instance of ApolloClient.
Open the src/index.js file and add the following code:
import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { HttpLink } from 'apollo-link-http'; const cache = new InMemoryCache(); const link = new HttpLink({ uri: 'https://graphql-pokemon.now.sh/' }) const client = new ApolloClient({ cache, link })
We first create an instance of InMemoryCache, then an instance of HttpLink and we pass in our GraphQL API URI. Next, we create an instance of ApolloClient and we provide the cache and link instances.
Connect the Apollo Client to React Components
After creating the instance of ApolloClient, we need to connect it to our React component(s).
We'll use the new Apollo hooks, which allows us to easily bind GraphQL operations to our UI.
We can connect Apollo Client to our React app by simply wrapping the root App component with the ApolloProvider component — which is exported from the @apollo/react-hooks package — and passing the client instance via the client prop.
The ApolloProvider component is similar to React's Context provider. It wraps your React app and places the client in the context, which enables you to access it from anywhere in your app.
Now let's import the ApolloProvider component in our src/index.js file and wrap the App component as follows:
The post How to Build a Web App with GraphQL and React appeared first on SitePoint.
by Ahmed Bouchefra via SitePoint https://ift.tt/325AIV2
0 notes
mbaljeetsingh · 7 years ago
Text
Introduction to Apollo Client With React for GraphQL
Tumblr media
GraphQL has been getting popular recently and is likely to replace the Rest API. In this tutorial, we will use Apollo Client to communicate with GitHub's GraphQL API. We will integrate Apollo Client with ReactJS, but you can use it with several other client platforms as well.
This tutorial does not cover how to start a React project, but you can use create-react-app to get started.
Once we have the react app ready to go, the next thing is to install the required modules.
Installing Modules
The following line installs all the required modules.
npm install apollo-client-preset react-apollo graphql-tag graphql --save
Now we can provide our component with a client.
Providing a Client to a Component
You can provide a client anywhere in your React component hierarchy. However, it is always a good practice to provide the component, wrapping your whole application, with the client.
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { ApolloProvider } from 'react-apollo'; import { ApolloClient } from 'apollo-client'; import { HttpLink } from 'apollo-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; const token = "YOUR_TOKEN"; const httpLink = { uri: 'https://api.github.com/graphql', headers: { authorization: `Bearer ${token}` } }; const client = new ApolloClient({ link: new HttpLink(httpLink), cache: new InMemoryCache() }); ReactDOM.render(<ApolloProvider client={client}><App/></ApolloProvider>, document.getElementById('root'));
Above you can see that we defined the uri for GitHub and also used a specific token for headers. You should be using your own token generated from GitHub. So don't forget to replace it with YOUR_TOKEN.
For this example, we defined the API token on the client side. However, you should not reveal your API token publicly. So it is always good to keep it on the server abstracted from the client side.
Notice that we have wrapped the <App/> component with ApolloProvider and used the client variable we created for the client prop.
GraphiQL Application
Before diving into the queries, I want to point out that there is a very handy tool called GraphiQL for testing your GraphQL queries. Before proceeding, make sure that you have downloaded it. 
Once you open GraphiQL, you need to set the GraphQL Endpoint and HTTP Headers.
GraphQL Endpoint: https://api.github.com/graphql
Header Name: Authorization
Header Value: Bearer YOUR_TOKEN
Of course, you need to replace YOUR_TOKEN with your own token. Do not forget to include the Bearer in front of your token when defining the Header Value.
If you do not want to download an application, you can also use the online GraphQL API Explorer for GitHub.
GraphQL Queries
Unlike a REST API with several end-points, the GraphQL API has only one end-point, and you only fetch what is defined by your query.
The documentation of GitHub's GraphQL API gives you more insight.
Also, the best part of the GraphiQL application is that it gives you access to documentation for queries right inside the application. You can see the sidebar on the right named Docs.
Let's start with the simplest query:
query{ viewer{ login } }
This query returns you the login information of the viewer. In this case, the viewer is you since you used your own API token.
In this tutorial, I will not give detailed information on queries. You can always refer to the documentation and try queries on GraphQL tools to see if you are getting the correct data.
Let's use the following query for the rest of the tutorial.
query($name: String!){ search(query: $name, last: 10, type: REPOSITORY) { edges { node { ... on Repository { id name description url } } } } }
This query searches for the last 10 repositories matching the specific input string, which we will define in our application.
It returns the id, name, description, and url for each result.
Using the GraphQL Query in a React Component
We need to import the two modules below to our React component to be able to define the query within the component and then pass the results to the component as props.
import gql from 'graphql-tag'; import { graphql } from 'react-apollo';
Here we assigned our query to a constant variable, but we haven't defined the name parameter yet.
const repoQuery = gql` query($name: String!){ search(query: $name, last: 10, type: REPOSITORY) { edges { node { ... on Repository { id name description url } } } } } `
Now we wrap our component with the graphql HOC (Higher Order Component) in order to define the query parameters, execute the query, and then pass the result as props to our component.
const AppWithData = graphql( repoQuery, { options: { variables: { name: "tuts" } } } )(App)
Below is the final version of our component.
import React, { Component } from 'react'; import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; class App extends Component { render() { return ( <div> </div> ); } } const repoQuery = gql` query($name: String!){ search(query: $name, last: 10, type: REPOSITORY) { edges { node { ... on Repository { id name description url } } } } } ` const AppWithData = graphql( repoQuery, { options: { variables: { name: "tuts" } } } )(App) export default AppWithData;
Note that we do not export the actual App component but the wrapped component, which is AppWithData.
Check the Data in the Console
Let's go ahead and add {console.log(this.props)} to the render method of your component.
class App extends Component { render() { console.log(this.props) return ( <div> </div> ); } }
When you check the console of your browser, you will see there are two object logs.
Inside each object, you will see the data property. This is provided to our component through the graphql HOC.
Notice that the first log has the loading: true property inside data, and the second log has loading: false and a new object named search, which is exactly the data we wanted to get.
Display the Data
Let's write some JSX to display the fetched data.
Since the search object is not initially there, we cannot directly try to render it. Therefore, first we need to check if we fetched the data and the search object is ready to be used.
In order to do that, we will simply use the loading information provided inside the data property.
If loading is true then we simply render the Loading text, otherwise the data itself.
class App extends Component { render() { return ( <div> {this.props.data.loading === true ? "Loading" : this.props.data.search.edges.map(data => <ul key={data.node.id}> <li style=><a href={data.node.url}>{data.node.name}</a></li> <li>{data.node.description}</li> </ul> )} </div> ); } }
I used the ?: ternary operator for basic inline conditional expressions. If loading is true we display Loading, and if it is false, we use the map function to iterate through our data array to display the information inside the <ul> and <li> elements.
This is just a basic example. You can use a regular if-else statement and return different results for your render method.
You can check the Apollo-Client-with-React repository, clone it on your computer, and play around.
P.S. Don't forget to replace the token variable with your own API token for GitHub.
Conclusion
We covered how to get started with Apollo Client for React. We installed the required modules, set up the client, and then provided it to our component at the top of the component hierarchy. We learned how to test GraphQL queries quickly before implementing them in our actual application. Finally, we integrated the query into a React component and displayed the fetched data.
via Envato Tuts+ Code https://ift.tt/2wqXsnX
0 notes
macronimous · 5 years ago
Text
Getting Cozy with useQuery and useMutation https://t.co/rjYfwz8Ysl #ReactHooks #ApolloClient https://t.co/M6dDInR0iJ
Getting Cozy with useQuery and useMutation https://t.co/rjYfwz8Ysl #ReactHooks #ApolloClient pic.twitter.com/M6dDInR0iJ
— Macronimous.com (@macronimous) August 22, 2020
from Twitter https://twitter.com/macronimous August 22, 2020 at 09:10PM via IFTTT
0 notes
rafi1228 · 6 years ago
Link
Build and deploy a full-stack React and GraphQL app from scratch with Apollo Boost, Express, and MongoDB
REACT WITH GRAPHQL
Created by Reed Barger
Last updated 6/2019
English
English [Auto-generated]
  What you’ll learn
Make practical, production-ready full-stack applications with React and GraphQL
Learn the GraphQL language, how to write queries and mutations both on the client and the server
Learn React-Apollo in-depth, including Query and Mutation Components, Nested Components, Optimistic UI and Refetching Queries
Understand how to use and set up Apollo Boost within React applications
Implement essential web app features such as user authentication, searching, and route protection
Authenticate your GraphQL application using JSON Web Tokens
Learn advanced React patterns such as higher-order components and render props
Discover many useful features of React Router 4
Learn and reinforce effective state management patterns
Animate your React app with popular component libraries such as React Pose
Deploy and redeploy full-stack React applications to the web
  Requirements – REACT WITH GRAPHQL
A basic familiarity with React
Some knowledge of JavaScript ES6 features is helpful, but not required
  Description
New! Additional Bonus Section: Updates for Full CRUD Functionality
This course is designed for anyone who wants to start building applications with React and GraphQL! In this course, we will build a recipe application from scratch with full authentication (sign up, sign in, sign out), as well as the ability to create, browse, search for, save, and delete recipes.  
Building this project will give you the skills to to create full-stack React and GraphQL applications from scratch for any theme you like!
This course presumes some experience with React, but if you are familiar with basic JavaScript concepts and have some knowledge of ES6 features, you will be able to follow along just fine. 
We will begin by building a backend with Node.js using the Express framework, then learn how tointegrate our backend with GraphQL. We’ll learn about essential topics within GraphQL such asqueries, mutations, schemas and resolvers, we’ll learn the GraphQL syntax and work extensively with GraphiQL to test our queries and mutations, after which we will move onto working with React. 
Then we will  build a React application and then connect it to our GraphQL-Express backend using Apollo Boost. We’ll cover all of the latest features of Apollo Boost and React Apollo, includingApolloClient, ApolloProvider/ApolloConsumer, as well as Query and Mutation components. On top of that, we’ll learn how to refetch queries, use optimistic UI, nest query and mutation components, use fragments and much more!
On top of learning all about Apollo Boost, we will use essential React libraries such as React Router (version 4) to provide routing for our application, learn how to make protected routes, use essential lifecycle methods, reinforce proper state management practices, use helpful ES6 features such as the object and array spread operators and object and array destructuring, as well as cleaner React practices such as the property initializer syntax.
Once we are done creating our application, we will go through the process of deploying to Heroku. We will create a postbuild script that will allow us to deploy our full-stack app using the Heroku CLI.
As a bonus section, we’re going to dive into some additional React component libraries (i.e. react-pose, react-spinners) that will give us the ability to further style and animate our application to make it production-ready, give users the ability to customize their recipes, and make our application responsive with CSS grid.
Who this course is for:
Any developer who wants to learn to make full-stack web applications with React and GraphQL from scratch
Size: 4.0GB
DOWNLOAD TUTORIAL
The post FULL-STACK REACT WITH GRAPHQL AND APOLLO BOOST appeared first on GetFreeCourses.Me.
0 notes
fbreschi · 6 years ago
Text
Updating ApolloClient cache and re-rendering data
http://bit.ly/2qXI14o
0 notes
supportivy · 6 years ago
Text
Mise à jour de requêtes spécifiques dans le cache ApolloClient et restitution des données
Mise à jour de requêtes spécifiques dans le cache ApolloClient et restitution des données
Mise à jour de requêtes spécifiques dans le cache ApolloClient et restitution des données
L’un des aspects les plus intéressants de l’utilisation d’ApolloClient est la mise en cache automatique en mémoire que vous obtenez immédiatement. Lors de la pagination de vos données, cela vous permet de revenir aux pages précédentes et d’avoir une transition incroyablement rapide. Mais parfois, vous ne…
View On WordPress
0 notes
webdesignersolutions · 6 years ago
Link
I have an app that has a login to access part of the site. I am using apollo-server-express and apollo-client for the app and when I go to my app on Chrome (FireFox too) everything works normally, but mobile browsers and safari will not start the session and store the cookie. I don’t understand this behavior. My client code is:
const client = new ApolloClient({    uri: \https://mrwetherall/graphql`,    credentials: ‘same-origin’,    clientState: {       defaults: defaultState,       resolvers: {} } })`
and my session code on the apollo-server-express is
app.use( session({          secret: process.env.SESSION_SECRET,          resave: false,          cookie: {             maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week          },          store: store,          saveUninitialized: false       }) )
What am I doing wrong?
Submitted August 08, 2019 at 04:22AM by rob_moose https://www.reddit.com/r/webhosting/comments/cnkct1/my_client_isnt_starting_a_session_on_some/?utm_source=ifttt
from Blogger http://webdesignersolutions1.blogspot.com/2019/08/my-client-isnt-starting-session-on-some.html via IFTTT
0 notes
ttorialcom · 7 years ago
Text
[Udemy] Full-Stack React with GraphQL and Apollo Boost
Build and deploy a full-stack React and GraphQL app from scratch with Apollo Boost, Express, and MongoDB.     What Will I Learn?   Make practical, production-ready full-stack applications with React and GraphQL Learn the GraphQL language, how to write queries and mutations both on the client and the server Learn React-Apollo in-depth, including Query and Mutation Components, Nested Components, Optimistic UI and Refetching Queries Understand how to use and set up Apollo Boost within React applications Implement essential web app features such as user authentication, searching, and route protection Authenticate your GraphQL application using JSON Web Tokens Learn advanced React patterns such as higher-order components and render props Discover many useful features of React Router 4 Learn and reinforce effective state management patterns Animate your React app with popular component libraries such as React Pose Deploy and redeploy full-stack React applications to the web Requirements A basic familiarity with React Some knowledge of JavaScript ES6 features is helpful, but not required Description This course is designed for anyone who wants to start building applications with React and GraphQL! In this course, we will build a recipe application from scratch with full authentication (signup, signin, signout), as well as the ability to create, browse, search for, save, and delete recipes.   Building this project will give you the skills to to create full-stack React and GraphQL applications from scratch for any theme you like! This course presumes some experience with React, but if you are familiar with basic JavaScript concepts and have some knowledge of ES6 features, you will be able to follow along just fine.  We will begin by building a backend with Node.js using the Express framework, then learn how tointegrate our backend with GraphQL. We'll learn about essential topics within GraphQL such asqueries, mutations, schemas and resolvers, we'll learn the GraphQL syntax and work extensively with GraphiQL to test our queries and mutations, after which we will move onto working with React.  Then we will  build a React application and then connect it to our GraphQL-Express backend using Apollo Boost. We'll cover all of the latest features of Apollo Boost and React Apollo, including ApolloClient, ApolloProvider/ApolloConsumer, as well as Query and Mutation components. On top of that, we'll learn how to refetch queries, use optimistic UI, nest query and mutation components, use fragments and much more! On top of learning all about Apollo Boost, we will use essential React libraries such as React Router (version 4) to provide routing for our application, learn how to make protected routes, use essential lifecycle methods, reinforce proper state management practices, use helpful ES6 features such as the object and array spread operators and object and array destructuring, as well as cleaner React practices such as the property initializer syntax. Once we are done creating our application, we will go through the process of deploying to Heroku. We will create a postbuild script that will allow us to deploy our full-stack app using the Heroku CLI. As a bonus section, we're going to dive into some additional React component libraries (i.e. react-pose, react-spinners) that will give us the ability to further style and animate our application to make it production-ready, give users the ability to customize their recipes, and make our application responsive with CSS grid. Who is the target audience? Any developer who wants to learn to make full-stack web applications with React and GraphQL from scratch source https://ttorial.com/full-stack-react-graphql-apollo-boost
0 notes
iyarpage · 7 years ago
Text
GraphQL Using the Apollo Framework: Getting Started
GraphQL is a data query language that simplifies client-server interactions over conventional REST or ad-hoc systems. It was opened to the community at large in 2015, and since then, has rapidly gained traction, standardizing the process of defining and delivering data to mobile and web apps alike.
The increasing popularity of GraphQL created a thriving, open-source community focused on everything from client libraries to IDE tools. One of the most popular of these projects is Apollo, a type-safe, caching GraphQL implementation available on a number of platforms.
The Apollo Framework makes it simple to consume a GraphQL schema, auto-generate data models, fetch and mutate data for any GraphQL endpoint, all on the client platform of your choice.
In this tutorial, you’ll learn how to use the Apollo framework for iOS to consume data from a GraphQL representation of SWAPI (the Star Wars API) and populate a simple reference app.
Along the way, you’ll learn about basic GraphQL concepts, such as data types, how to define queries, and how to simplify consuming repetitious code using fragments.
Strap in and get ready to go to a GraphQL galaxy far, far away!
Getting Started
To kick things off, start by downloading the materials for this tutorial (you can find a link at the top or bottom of this tutorial)
This project uses Cocopoads, so open the project by double-clicking JediArchives.xcworkspace in Finder.
There’s a standard navigation structure, ready to be filled up with Wookies and Jedi. But first, you’re going to install and start the server that will power the app.
Running the SWAPI GraphQL Server
Before you start working on the Jedi Archives app, you’re going to need a GraphQL server for it to connect to. The starter project includes a pre-configured Node.js project that will serve SWAPI on your local machine.
Note: The next few steps assume you’ve installed the npm package manager. More info on Node.js and npm can be found in this tutorial.
Open Terminal and navigate to the bin directory of the starter project. Next, run the following command to install the dependencies and bootstrap the project:
./install_server.sh
Finally, run the following command to start up the server:
./start_server.sh &
After some initial Terminal output, you should see a message telling you the server is now running on port 8080. You now have a GraphQL endpoint for SWAPI running on your machine.
Note: The & on the end runs the server in the background so that you may continue to use your terminal session. To shut the server down, enter fg at the shell prompt, then press Control-C.
Xcode Configuration
One of Apollo’s best features is its ability to generate statically-typed Swift queries and models based on any GraphQL schema. To generate these, you use a tool called Apollo Codegen to consume the schema and generate the Swift output.
In Terminal, run the following command to install Apollo Codegen:
npm install -g apollo-codegen
Next you’re going to add a Run Build Script phase to your Xcode project that executes apollo-codegen whenever you build, to ensure you always have an updated set of Swift models and queries.
In Xcode, select JediArchives in the project navigator, then select the JediArchives target and click the Build Phases tab. Click the “+” button and select New Run Script Phase.
Expand the new run phase and insert the following script into the script text area below the Shell variable:
if which apollo-codegen >/dev/null; then APOLLO_FRAMEWORK_PATH="$(eval find $FRAMEWORK_SEARCH_PATHS -name "Apollo.framework" -maxdepth 1)" if [ -z "$APOLLO_FRAMEWORK_PATH" ]; then echo "warning: Couldn't find Apollo.framework in FRAMEWORK_SEARCH_PATHS; make sure to add the framework to your project." exit 0 fi cd "${SRCROOT}/${TARGET_NAME}/GraphQL" $APOLLO_FRAMEWORK_PATH/check-and-run-apollo-codegen.sh generate \ $(find . -name '*.graphql') \ --schema schema.json \ --output Generated/GraphQLAPI.swift else echo "Skipping Apollo code generation" fi
The bulk of the script ensures the tools you expect are present. The most important line is the one that executes check-and-run-apollo-codegen.sh.
Taking each parameter in turn:
generate $(find . -name '*.graphql'): Invokes the generate command and passes any files with the extension .graphql. These types of files contain the GraphQL queries and fragments you define. You’ll learn more about this later.
--schema schema.json: Indicates the location of the GraphQL schema file relative to the current directory. The GraphQL schema defines all the data types and their relationships for a given endpoint.
--output Generated/GraphQLAPI.swift: Indicates the Swift file that houses the generated code. This file is updated every time this script is run and contains the code you’ll use to interact with the GraphQL endpoint. You should never modify this file directly.
Now the script is ready, single-click the name of the Run Script Phase and change it to Apollo GraphQL so it’s clear what the phase is doing. Finally, since you’ll be writing code that consumes this generated code, this script needs to run prior to the rest of your code compiling.
Click and drag the phase so it appears right before the “Compile Sources” phase. When you’re done, the Build Phases screen should look similar to the following:
Well done young Padawan! It’s time to become a fully-fledged Jedi Knight by writing some code.
Populating the Films Screen
The first screen you’re going to put together will show a list of all the Star Wars films. In a traditional REST-based app, this would be about the time when you’d have to create a web client of some sort, using something like Alamofire to wrap each API endpoint, define a series of structs or classes to represent result data, and configure a JSON mapping tool to glue it all together.
Instead, you’re going to use GraphQL and Apollo to achieve all of this — with far less effort on your part.
The first thing to do is create a wrapper around the Apollo client to house basic configuration and maintain a static instance to use across the various view controllers.
First, open Apollo.swift inside the GraphQL folder and import the Apollo framework:
import Apollo
Next, add the following class definition:
class Apollo { // 1 static let shared = Apollo() // 2 let client: ApolloClient init() { // 3 client = ApolloClient(url: URL(string: "http://localhost:8080")!) } }
Here’s a rundown of what you just added:
You declare a static instance of the Apollo wrapper class to expose it as a singleton.
Next, you declare a variable to house an instance of ApolloClient which is the class through which you’ll interact with GraphQL.
Finally, you initialize the ApolloClient instance, supplying the URL of the GraphQL server you’re running on your local machine.
Now you’ve added the ability to interact with Apollo, it’s time to define your first GraphQL query.
GraphQL is, at its core, a data query language. A GraphQL server defines a schema, including all the objects, their fields and types, as well as relationships, in a standard JSON format. You configured Apollo to consume the schema in the last section. Any client can use this schema to construct queries for any subset of data, including primitive fields and nested object references and lists.
Allowing the client to determine exactly how to fetch the data is a key feature that makes GraphQL so powerful. Throughout the rest of this tutorial, you’re going to see this concept in action.
Open Queries.graphql and add the following:
query AllFilms { # 1 allFilms { # 2 films { # 3 id title releaseDate } } }
This is a very basic query. Here’s what each section means:
This statement defines the top level query collection from which you’re requesting data. In this case, allFilms returns, unsurprisingly, all films.
The allFilms collection returns a list of intermediate FilmConnection objects, so here you request the films attribute, which will include a list of actual Film objects.
Finally, you define the attributes you want to request from each Film object.
At this point, build the project and then open GraphQLAPI.swift: the file where Apollo drops generated code. You should now see a class named AllFilmsQuery. This class contains the Swift representation of the query itself, as well as structs that represent the result data.
Now you’ve defined a query and have generated result models, you need to map the film results to view models that are consumed by your view controllers.
Open Models.swift and add the following initializer to the RefItem class:
init(film: AllFilmsQuery.Data.AllFilm.Film) { id = film.id label = film.title ?? "" value = film.releaseDate ?? "" }
RefItem is a general-use model that will be used across the app to represent any data type that references other data. These items are rendered in table cells with a left-aligned label and right-aligned value. In the above code, you create an initializer that takes an instance of AllFilmsQuery.Data.AllFilm.Film, which is the type of the embedded Film result object returned by the AllFilms query.
The last thing to do here is to execute the query and populate the first screen of the app.
Open FilmsViewController.swift and replace loadFilms() with the following:
func loadFilms() { // 1 let query = AllFilmsQuery() Apollo.shared.client.fetch(query: query) { results, error in // 2 if let films = results?.data?.allFilms?.films?.compactMap({$0}) { // 3 let models = films.map(RefItem.init) // 4 let sections: [Section] = [ .references(title: NSLocalizedString("Films", comment: ""), models: models) ] // 5 self.dataSource.sections = sections self.tableView.reloadData() } else if let error = error { print("Error loading data \(error)") } } }
There’s a lot going on here, so to explain line-by-line:
First, you execute the AllFilms query by passing an instance of it to the shared Apollo client. ApolloClient translates the query to JSON, executes the HTTP call, maps the response to the generated structs, and invokes the provided completion handler with either result data or an error if there was a failure.
Next, you unwrap a chain of optionals and compactMap to produce a list of film results. If you inspect the type of results?.data?.allFilms?.films, you’ll see it’s [Film?]?. Therefore compactMap is used to produce a list without optional objects.
Here you map the film results to RefItem using the initializer you added previously.
Now you create a list of Section enums that represent the sections displayed in the table view. In this case there is just one section of films.
Finally, you set the list of sections on the table view’s data source and reload the table view to render the data to the screen.
Build and run; you should see a list of Star Wars films:
Excellent! Your app is starting to take shape. In the next section, you’ll flesh out a detail screen to show even more data about each film.
Note: The current SWAPI GraphQL data doesn’t include the most recent Star Wars films, so this app is confined to the pre-Disney era. Unfortunately (or fortunately, depending on your views), it does contain all three prequel films.
Populating the Film Detail Screen
Seeing a list of Star Wars movies is great, but seeing details for each film would be even better. GraphQL makes it a snap to retrieve extended info for each film. You’re going to define a new query for film details and use the results of that query to populate the film detail view controller.
Open Queries.graphql and add the following query:
# 1 query FilmDetail($id: ID) { # 2 film(id: $id) { # 3 title episodeID releaseDate director # 4 characterConnection(first: 10) { # 5 characters { id name } } } }
This query is similar to the “All Films” query you defined in the previous section, but there are a few new concepts to note:
In the query definition, unlike AllFilms, FilmDetail takes an argument for the film ID. This argument can be referenced anywhere within the query and will be automatically included as an argument of the initializer in the generated Swift query.
Here you specify the film collection and pass the film ID to pull back a single Film object.
As in the previous query, you specify the fields you’d like to fetch from the Film object as part of the query.
Here you specify you want to include characterConnection, which is a list of related characters appearing in this film. You specify first: 10 to include a max of 10 characters.
Finally, you specify the characters list to get the actual list of characters, as well as the fields you care about for each individual character.
Build the app to generate the appropriate Swift code that references the new query and objects. Now you have a query you can use to fetch film detail, you’re going to add some code to populate the film detail screen.
Open Models.swift and add the following initializer to RefItem:
init(character: FilmDetailQuery.Data.Film.CharacterConnection.Character) { id = character.id label = character.name ?? "" value = nil }
This new initializer takes an instance of the Character object from the FilmDetail query. You’ll see FilmDetail used in the next step when you map the query results to UI models. When you render a character in the table view, the cell will only contain that character’s name; you supply nil for value.
Open FilmDetailViewController.swift and replace loadFilmData() with the following:
func loadFilmDetail() { // 1 let query = FilmDetailQuery(id: filmID) Apollo.shared.client.fetch(query: query) { result, error in // 2 if let film = result?.data?.film { // 3 self.navigationItem.title = film.title ?? "" // 4 let infoItems: [InfoItem] = [ InfoItem(label: NSLocalizedString("Title", comment: ""), value: film.title ?? "NA"), InfoItem(label: NSLocalizedString("Episode", comment: ""), value: "\(film.episodeId ?? 0)"), InfoItem(label: NSLocalizedString("Released", comment: ""), value: film.releaseDate ?? "NA"), InfoItem(label: NSLocalizedString("Director", comment: ""), value: film.director ?? "NA") ] // 5 var sections: [Section] = [ .info(title: NSLocalizedString("Info", comment: ""), models: infoItems) ] // 6 let characterItems = film.characterConnection?.characters? .compactMap({$0}).map({RefItem(character: $0)}) // 7 if let characterItems = characterItems, characterItems.count > 0 { sections.append(.references(title: NSLocalizedString("Characters", comment: ""), models: characterItems)) } // 8 self.dataSource.sections = sections self.tableView.reloadData() } else if let error = error { print("Error loading data \(error)") } } }
You should see some similarities between this and loadFilms() you created above. Here’s what you’re doing in detail:
First, you create an instance of FilmDetailQuery and pass the ID for the film this view controller should display. With that query object, you execute the fetch via the Apollo client.
Next, you use optional binding to get the film from the query result.
Then, you set the title of the screen to the name of the film.
You create a list of InfoItem models to represent each attribute of the film you want to render to the UI. Each item has a title and value, and there is some nil coalescing to account for missing values.
Next you define a Section for the film info section, providing the list of info items you just created.
The second section of this detail screen is a list of characters that appear in this film. You map the character list from the film result to a list of RefItem objects.
Again, you create a new Section, to show the character items.
Finally, you update the data source and reload the table view to render the data.
Build and run, and tap on any of the films in the main list to see the details for that film. The resulting screen should look similar to the following:
You’ve taken your first step into a larger world. In the next section, you’ll wrap up the app by populating a character detail screen.
Populating the Character Detail Screen
Your Star Wars app is looking great! All that’s left is to add a screen for viewing character details and you’ll be a bona fide Jedi Master. Once again, you’re going to start by adding a query that fetches only the data you need to populate this screen. Open Queries.graphql and add the following text:
query CharacterDetail($id: ID) { person(id: $id) { name birthYear eyeColor gender hairColor skinColor homeworld { name } filmConnection(first: 10) { films { id title releaseDate } } } }
This query is very similar to the film detail query you defined in the previous section. The data you’re requesting from each object in the films list is exactly the same data you’re requesting for films in the AllFilms query.
If you leave the queries as they are, you’ll end up with two different Film structs, each scoped to their parent query objects. It’s not awful; but code that consumes films in this form will need multiple paths for each parent object type. What’s more, it’s likely if you ever request more film data through one of these queries, you’ll probably want that same data in the other query. What you really want is a way to generalize this query section into something common.
GraphQL has just the tool to solve this problem: fragments.
Add the following to the top of Queries.graphql:
fragment ListFilmFragment on Film { id title releaseDate }
Here you define the name of the fragment, ListFilmFragment, and the object to which it applies, Film. Then you simply specify the fields you’d like to request. Now you can replace those fields in any query with ... ListFilmFragment and those fields will be requested as if you had explicitly specified them.
Even better, instead of having Film structs specific to each query, each query result will now return this data as part of a globally scoped ListFilmFragment. This drastically simplifies code that consumes film objects.
Now you’ve defined ListFilmFragment, it’s time to use it to improve a few queries. Still in Queries.graphql, replace the AllFilms query with the following:
query AllFilms { allFilms { films { ...ListFilmFragment } } }
Since the CharacterDetail query wants the same data for its film list, replace it with the following:
query CharacterDetail($id: ID) { person(id: $id) { name birthYear eyeColor gender hairColor skinColor homeworld { name } filmConnection(first: 10) { films { ...ListFilmFragment } } } }
Build your project to update the generated code. You’ve cleaned up your queries, so you also need to change the consuming code to take advantage of the newly added ListFilmFragment.
Open Models.swift and change the first initializer of RefItem to this:
init(film: ListFilmFragment) { id = film.id label = film.title ?? "" value = film.releaseDate ?? "" }
You’ve changed the film parameter type so it now consumes ListFilmFragment instead of the film type from the AllFilms query. This will let you use this same constructor for mapping results from both AllFilmsQuery and CharacterDetailQuery. Score one Republic credit for code reuse and a Bantha for simpler logic!
Since you changed the RefItem initializer, you’re going to need to adjust the code that uses it.
Open FilmsViewController.swift and find the following line in loadFilms():
if let films = results?.data?.allFilms?.films?.compactMap({$0}) {
Replace with the following:
if let films = results?.data?.allFilms?.films?.compactMap({$0}).map({$0.fragments.listFilmFragment}) {
Instead of mapping the film objects directly, you’re mapping listFilmFragment that lives on a property named fragments. Every Apollo result that includes fragments has a fragments property and it’s where you’ll find, er, the fragments.
Now your Jedi temple is in better order, the only thing left is to finish up the character detail screen. Open CharacterDetailViewController.swift and replace loadCharacter() with the following:
func loadCharacter() { // 1 let query = CharacterDetailQuery(id: characterID) Apollo.shared.client.fetch(query: query) { (result, error) in // 2 if let character = result?.data?.person { // 3 self.navigationItem.title = character.name ?? "" // 4 let infoItems: [InfoItem] = [ InfoItem(label: NSLocalizedString("Name", comment: ""), value: character.name ?? "NA"), InfoItem(label: NSLocalizedString("Birth Year", comment: ""), value: character.birthYear ?? "NA"), InfoItem(label: NSLocalizedString("Eye Color", comment: ""), value: character.eyeColor ?? "NA"), InfoItem(label: NSLocalizedString("Gender", comment: ""), value: character.gender ?? "NA"), InfoItem(label: NSLocalizedString("Hair Color", comment: ""), value: character.hairColor ?? "NA"), InfoItem(label: NSLocalizedString("Skin Color", comment: ""), value: character.skinColor ?? "NA"), InfoItem(label: NSLocalizedString("Home World", comment: ""), value: character.homeworld?.name ?? "NA") ] // 5 var sections: [Section] = [ .info(title: NSLocalizedString("Info", comment: ""), models: infoItems) ] // 6 let filmItems = character.filmConnection?.films?.compactMap({$0}) .map({RefItem(film: $0.fragments.listFilmFragment)}) if let filmItems = filmItems, filmItems.count > 0 { sections.append(.references(title: NSLocalizedString("Appears In", comment: ""), models: filmItems)) } // 7 self.dataSource.sections = sections self.tableView.reloadData() } else if let error = error { print("Error loading data \(error)") } } }
Again, this method is similar to the other data loading methods you’ve written. However for the sake of clarity, here’s what’s happening:
First, you initialize and execute CharacterDetailQuery, providing the character ID.
Next, you use optional binding to get the character from the result object.
You set the title of the view controller to the character’s name.
Then you create a list of InfoItem objects to represent the various character attributes you requested.
Here you create the first table view section, passing the InfoItem objects as the contents.
In this block, you make use of the films, again using the ListFilmFragment, to populate a table view section with films this character has appeared in.
Finally, you update the data source’s section list and reload the table view to render the new data to the UI.
Build and run. Tap first on any film, then on any character in the second section. You should see a screen similar to the following:
Because you’ve closed the loop by including a films list in the character screen, you can now dive endlessly through films and characters, exploring the entirety of the Star Wars universe. On behalf of the Rebellion, congratulations on a job well done!
Where to Go From Here?
You can download the final project using the link at the top or bottom of this tutorial.
GraphQL is an extremely powerful technology, and through this tutorial, you’ve seen how it can simplify the development of a data-driven app when paired with the Apollo framework.
There are more concepts to explore in GraphQL and Apollo, such as mutations, variables, and caching to name just a few. The official GraphQL and Apollo sites are both great places to continue learning.
If you have any comments or questions about this tutorial, please join the forum discussion below!
The post GraphQL Using the Apollo Framework: Getting Started appeared first on Ray Wenderlich.
GraphQL Using the Apollo Framework: Getting Started published first on https://medium.com/@koresol
0 notes
macronimous · 5 years ago
Text
Getting Cozy with useQuery and useMutation https://t.co/9ainKzR6m0 #ReactHooks #ApolloClient https://t.co/HEsYTOVhKU
Getting Cozy with useQuery and useMutation https://t.co/9ainKzR6m0 #ReactHooks #ApolloClient pic.twitter.com/HEsYTOVhKU
— Macronimous.com (@macronimous) June 2, 2020
from Twitter https://twitter.com/macronimous June 02, 2020 at 11:50PM via IFTTT
0 notes
rafi1228 · 6 years ago
Link
Build and deploy a full-stack React and GraphQL app from scratch with Apollo Boost, Express, and MongoDB
What you’ll learn
Make practical, production-ready full-stack applications with React and GraphQL
Learn the GraphQL language, how to write queries and mutations both on the client and the server
Learn React-Apollo in-depth, including Query and Mutation Components, Nested Components, Optimistic UI and Refetching Queries
Understand how to use and set up Apollo Boost within React applications
Implement essential web app features such as user authentication, searching, and route protection
Authenticate your GraphQL application using JSON Web Tokens
Learn advanced React patterns such as higher-order components and render props
Discover many useful features of React Router 4
Learn and reinforce effective state management patterns
Animate your React app with popular component libraries such as React Pose
Deploy and redeploy full-stack React applications to the web
Requirements
A basic familiarity with React
Some knowledge of JavaScript ES6 features is helpful, but not required
Description
New! Additional Bonus Section: Updates for Full CRUD Functionality
This course is designed for anyone who wants to start building applications with React and GraphQL! In this course, we will build a recipe application from scratch with full authentication (sign up, sign in, sign out), as well as the ability to create, browse, search for, save, and delete recipes.
Building this project will give you the skills to to create full-stack React and GraphQL applications from scratch for any theme you like!
This course presumes some experience with React, but if you are familiar with basic JavaScript concepts and have some knowledge of ES6 features, you will be able to follow along just fine.
We will begin by building a backend with Node.js using the Express framework, then learn how tointegrate our backend with GraphQL. We’ll learn about essential topics within GraphQL such asqueries, mutations, schemas and resolvers, we’ll learn the GraphQL syntax and work extensively with GraphiQL to test our queries and mutations, after which we will move onto working with React.
Then we will  build a React application and then connect it to our GraphQL-Express backend using Apollo Boost. We’ll cover all of the latest features of Apollo Boost and React Apollo, including ApolloClient, ApolloProvider/ApolloConsumer, as well as Query and Mutation components. On top of that, we’ll learn how to refetch queries, use optimistic UI, nest query and mutation components, use fragments and much more!
On top of learning all about Apollo Boost, we will use essential React libraries such as React Router (version 4) to provide routing for our application, learn how to make protected routes, use essential lifecycle methods, reinforce proper state management practices, use helpful ES6 features such as the object and array spread operators and object and array destructuring, as well as cleaner React practices such as the property initializer syntax.
Once we are done creating our application, we will go through the process of deploying to Heroku. We will create a postbuild script that will allow us to deploy our full-stack app using the Heroku CLI.
As a bonus section, we’re going to dive into some additional React component libraries (i.e. react-pose, react-spinners) that will give us the ability to further style and animate our application to make it production-ready, give users the ability to customize their recipes, and make our application responsive with CSS grid.
Who is the target audience?
Any developer who wants to learn to make full-stack web applications with React and GraphQL from scratch
Created by Reed Barger Last updated 9/2018 English English [Auto-generated]
Size: 4.13 GB
   Download Now
https://ift.tt/2pJ23fj.
The post Full-Stack React with GraphQL and Apollo Boost appeared first on Free Course Lab.
0 notes
rafi1228 · 6 years ago
Link
Build a complete Pinterest-inspired full-stack app from scratch with Vue, GraphQL, Apollo 2, Vuex, and Vuetify
What you’ll learn
Learn in-depth how to use Apollo Server 2 and Apollo Boost to create powerful full-stack apps
Learn how to handle errors on the client and server with Apollo / GraphQL
Be able to implement session-based JWT authentication to GraphQL applications
Integrate Apollo with Vuex for more reliable and scalable state management
Implement infinite scrolling functionality using Vue-Apollo
Deploy full-stack JavaScript / GraphQL applications using Heroku and Netlify
Learn how to write queries and mutations in the GraphQL language on both the client and server
Make use of many useful MongoDB methods and features
Be able to create attractive, sophisticated UIs using the Vuetify CSS framework
Become more familiar with all the best ES6 / 7 features such as async / await, destructuring, spread operators, arrow functions, etc
Requirements
A basic familiarity with Vue
A basic understanding of ES6 JavaScript will help, but it’s not required
Description
Includes Apollo Server 2, Apollo Boost and the very new Vue CLI 3!
Interested in building next-level apps with Vue and GraphQL? Look no further!
This course is your one-stop guide to learning…
Complete CRUD functionality (create, read, update, and delete) with Vue and GraphQL / Apollo 2
The latest and greatest Apollo tools: Apollo Server 2, Apollo Boost and Vue Apollo
Using the new Vue CLI 3 to create/scaffold Vue apps, add plugins and deploy to the web
GraphQL Syntax, including types (scalar/object), and creating schemas with typeDefs
Writing and executing GraphQL queries and mutations on both the client and server
Essential Apollo features  such as the update function, optimistic responses, and refetching queries
Error handling with Apollo Server 2 with the new AuthorizationError and formatErrors features
Role-based user authentication with JSON Web Tokens
State management with Vuex, in concert with ApolloClient
Stunning UIs using mobile-first design with the Vuetify, a Material Design Component Library for Vue
Form Validation with the help of Vuetify
Vue Router (including protected routes, page transitions, router props, and dynamic segments)
Building resolvers using many MongoDB methods and operators
Search Functionality with MongoDB
Advanced GraphQL features such as infinite scrolling
GraphQL shorthands to make our schemas and queries concise, such as inputs and fragments
Lots of work with the Chrome/Firefox Vue Dev Tools Extension to Debug Vue / Vuex / Apollo
Using the service Now to deploy Vue / GraphQL Apps
Advanced UI tricks, including notifications and loading skeletons
And more…
What will we be building? What is the course based on?
This entire course within the context of a practical application that we will build literally from the first line of code to live deployment on the web.
We’ll be building an image-sharing social application called VueShare, similar to that of Pinterest or Instagram. Authenticated users of our app will be able to like and unlike, share, comment on, search for, edit, and delete image-related posts.
How does the course develop as we go along?
In the beginning of the course, we’ll cover the basic GraphQL / Apollo concepts that we need to get started, then dive into building our app. We’ll build out our backend, cover creating a GraphQL server and database (hosted with MLab), and how to write resolver functions with MongoDB. Then we’ll move over to the frontend, create our Vue app and connect it with our backend, develop an interface and build client-side functionality with Vue, Vuetify, and Vue Apollo / Vuex. We’ll learn how to write and execute queries and mutations using Apollo to our backend to get and modify what we need. Once we cover and integrate all the essential features of our application (listed above), we’ll move on to deploying our app to the web. After deployment, for those who want to stick around and make their app truly production-ready, we’ll cover a number of cool features to make our app more functional, attractive and reliable.
I wanted to make this course as comprehensive as I could, but also give you the fast track to learning new technologies in an engaging way. GraphQL is an exciting new technology in the web development community and new Apollo releases such as Apollo Server 2 and Apollo Boost have made working with GraphQL easier than ever.
There’s never been a better time to start working with GraphQL, especially as a JavaScript developer. Join me and let’s get started!
Who is the target audience?
Anyone who wants to learn how to build full-stack applications with Vue and GraphQL!
Created by Reed Barger Last updated 9/2018 English English [Auto-generated]
Size: 4.97 GB
   Download Now
https://ift.tt/32iX1b3.
The post Full-Stack Vue with GraphQL – The Ultimate Guide appeared first on Free Course Lab.
0 notes