I have created an app using Next.js, Apollo, and I fetch data with WPGraphQL. So far I have been able to fetch data using getStaticProps()
and getServerSideProps()
on pages files.
However it doesn't work with client-side rendering in Components as it either keep loading or logs data as "undefined". The weird thing is the same implementation works when I fetch data from a non-WPGraphQL url.
Here is my code.
_app.js
import 'bootstrap/dist/css/bootstrap.css';
import '../public/css/styles.css';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { ApolloProvider } from "@apollo/client";
import client from "../apollo-client";
function MyApp({ Component, pageProps }) {
return (
<>
<ApolloProvider client={client}>
<Header />
<Component {...pageProps} />
<Footer />
</ApolloProvider>
</>
);
}
export default MyApp;
./apollo-client.js
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
uri: process.env.WP_API_URL,
cache: new InMemoryCache(),
headers: {
authorization: process.env.WP_AUTHORIZATION,
},
});
export default client;
./components/ClientOnly.js
import { useEffect, useState } from "react";
export default function ClientOnly({ children, ...delegated }) {
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => {
setHasMounted(true);
}, []);
if (!hasMounted) {
return null;
}
return <div {...delegated}>{children}</div>;
}
.components/Articles.js
import { useQuery, gql } from "@apollo/client";
const QUERY = gql`
query Articles {
posts(where: { categoryName: "articles", status: PUBLISH}, last: 3) {
edges {
node {
author {
node {
name
}
}
featuredImage {
node {
sourceUrl
srcSet
}
}
title
slug
}
}
}
}
`;
export default function Articles() {
const { data, loading, error } = useQuery(QUERY);
if (loading) {
return <h2>Loading...</h2>;
}
if (error) {
console.error(error);
return null;
}
const posts = data.posts.edges.map(({ node }) => node);
console.log('THis is DATA',data)
return (
<div>
...