0

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>
...
I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
benjdan
  • 169
  • 2
  • 6
  • Are you getting any errors in the browser's console and/or in devtools network tab? Keep in mind that you need to prefix environment variables with `NEXT_PUBLIC_` to expose them to the browser. – juliomalves Oct 08 '21 at 18:11
  • Hi, I am not getting anything logged but I am gonna look at the prefix environment, thanks. – benjdan Oct 08 '21 at 20:51
  • I modified the prefix and I am now getting the data showing up in my terminal but not logged in my browser. – benjdan Oct 08 '21 at 21:25

0 Answers0