apollo-client GraphQL in nextJS
Wed Dec 20 2023 15:50:34 GMT+0000 (Coordinated Universal Time)
Saved by
@devbymohsin
#javascript
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
// Initialize Apollo Client
const client = new ApolloClient({
uri: 'http://localhost:4000/GraphiQL',
cache: new InMemoryCache(),
});
// GraphQL query
const GET_BOOKS = gql`
query {
getBook(id: 6) {
author
name
}
getAllBooks {
name
}
bookInfo(id:"book1"){
name
author
}
}
`;
// Function to fetch data
export async function getBooks() {
const { data } = await client.query({
query: GET_BOOKS,
});
return data;
}
// GraphQL mutation
const CREATE_BOOKS = gql`
mutation{
createBook(author: "mohsin khan", name: "allah akbar"){
author
name
id
}
}
`;
// Function to fetch data
export async function getBooks() {
const { data } = await client.mutate({
mutation: CREATE_BOOKS,
});
return data;
}
// call this in page.js
import { getBooks } from './apollo-client';
const graphql = () => {
getBooks().then((data) => {
console.log(data);
});
}
graphql()
content_copyCOPY
Comments