Building a React Native App with Apollo Client and GraphQL: A Step-by-Step Guide
First, let’s start with setup and installation:
npm install graphql graphql-tag
We first need to install two packages: graphql and @apollo/client.
npm install graphql @apollo/client
With these installed, let’s import the three symbols we need from the @apollo/client package in src/index.js:
import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";
In my case i am using Expo router so i will Setup client in in _layout of the the app directory , you can also setup using context API
The ApolloClient class
As you’d expect, ApolloClient is the class that represents Apollo Client itself. We create a new client instance like so:
const client = new ApolloClient({
// options go here
})
We need to provide a couple of options to the constructor. The first is the uri option, which we use to specify the location of our GraphQL server. Our server is running locally at localhost:4000, so the uri option looks like this:
In my case I will be using Hygraph as a headles CMS which provide out of the box support for the grapgql
Feel free to use any graphql solution out there like Strapi , contentful or Setup your own server .
That’s all we need to configure our client! Here’s the full call:
const client = new ApolloClient({
uri: "https://localhost:4000", //replace with own server
cache: new InMemoryCache(),
});
The ApolloProvider component
The ApolloProvider component uses React's Context API to make a configured Apollo Client instance available throughout a React component tree. To use it, we wrap our app's top-level components in the ApolloProvider component and pass it our client instance as a prop:
领英推荐
import { Stack } from "expo-router/stack";
import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";
const client = new ApolloClient({
uri: "replace with your link ",
cache: new InMemoryCache(),
});
export default function Layout() {
return (
<ApolloProvider client={client}>
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
</Stack>
</ApolloProvider>
);
}
For React Application this will look like this
root.render(
<React.StrictMode>
<ApolloProvider client={client}>
<GlobalStyles />
<Pages />
</ApolloProvider>
</React.StrictMode>
);
After this you will write Query to fetch details from the server in my case i am using Hygraph API playground
This is how the the Playground looks in Hygraph
The query for fetching all the sneakers data from the server will look like this, and this is how you write it using graphql-tag:
import gql from "graphql-tag";
const GetShoes = gql`
query GetShoes {
shoes {
category {
id
name
shoes {
name
price
description
image {
id
url
}
}
}
}
}
`;
I am using useQuery hook from Apollo Client to fetch data :
let { data , loading ,error } = useQuery(GetShoes);
when you open the React native dev tools you will see the response from the server loggged , You might have noticed that you did not pass any Authorization Header in the the Request Tab .that is because By default, Hygraph doesn’t require authentication to interact with the GraphQL Content API for logged-in CMS users
import gql from "graphql-tag";
import { useQuery } from "@apollo/client";
const { width } = Dimensions.get("window");
const GetShoes = gql`
query GetShoes {
shoes {
category {
id
name
}
name
price
description
image {
id
url
}
}
}
`;
export default function Tab() {
const { data, loading, error } = useQuery(GetShoes);
if (loading) return <Text>Loading...</Text>;
if (error) return <Text>Error! {error.message}</Text>;
const renderShoeItem = ({ item }) => (
<Card style={styles.card}>
<Card.Cover source={{ uri: item.image.url }} style={styles.cardImage} />
<Card.Content style={styles.cardContent}>
<Title style={styles.shoeName}>{item.name}</Title>
<Paragraph style={styles.shoePrice}>${item.price}</Paragraph>
</Card.Content>
</Card>
);
return (
<PaperProvider theme={PaperDarkTheme}>
<View style={styles.container}>
<FlatList
data={data.shoes}
renderItem={renderShoeItem}
keyExtractor={(item) => item.image.id}
numColumns={2}
contentContainerStyle={styles.listContent}
/>
</View>
</PaperProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#696969", // Dark background
padding: 16,
},
listContent: {
paddingBottom: 16,
},
card: {
width: (width - 48) / 2,
margin: 8,
backgroundColor: "#303030", // Dark card color
borderRadius: 10,
},
cardImage: {
height: 200,
},
cardContent: {
padding: 8,
},
shoeName: {
fontSize: 16,
fontWeight: "bold",
color: "white",
},
shoePrice: {
fontSize: 14,
color: "#ccc",
},
});
This is the final UI for the Sneakers app, where we are displaying the sneaker cards using FlatList. You can define your own style and try to customize it, adding more functionality to the project. I will provide the link to the sandbox once it is deployed.
Before starting with GraphQL and Apollo, make sure to go through some tutorials provided in the documentation to familiarize yourself with the basics.