0

As the title said, I can't get the response data from graphql inside Home component, even though I can fetch data from the same code in getStacticProps. The button with onClick function loadMore doesn't work. I want whenever I click on the load more button, 3 more posts will be loaded. When I tried to log graphcms variable inside loadMore, I get URL undefined

import { GraphQLClient } from 'graphql-request';
import { blogList, slugList } from './api';

const graphcms = new GraphQLClient(process.env.GRAPHQL_API);

export async function getStaticProps() {
  const skip = 0;
  const {
    postsConnection: { edges },
  } = await graphcms.request(blogList, {
    skip,
  });
  return {
    props: {
      edges,
    },
    revalidate: 30,
  };
}

export default function Home({ edges }) {    

  const [skip, setSkip] = useState(3);
  const [postList, setPostList] = useState(edges);

  const loadMore = async () => {
    const {
      postsConnection: { edges },
    } = await graphcms.request(blogList, {
      skip,
    });

    console.log(posts);
    setPostList((value) => [...value, ...edges]);
    setSkip((skip) => skip + 3);
  };

  return (
    <>
      <main>
            <div className='cards__grid'>
              {postList.map((post) => (
                <BlogCard
                  title={post.node.title}
                  src={post.node.coverPhoto.url ? post.node.coverPhoto.url : ''}
                  alt={post.node.alt}
                  key={post.node.id}
                  slug={post.node.slug}
                />
              ))}
            </div>
          

          <button type='button' className='load-more' onClick={loadMore}>
            Load more
          </button>
          
        </main>

      </div>
    </>
  )
}

index.js

import { gql } from 'graphql-request';

export const blogList = gql`
  query Posts($skip: Int) {
    postsConnection(orderBy: datePublished_DESC, first: 3, skip: $skip) {
      edges {
        node {
          id
          title
          slug
          coverPhoto {
            url
          }
        }
      }
      pageInfo {
        pageSize
        startCursor
        endCursor
      }
    }
  }
`;

api/index.js

Tue An
  • 11
  • Environment variables need to be prefixed with `NEXT_PUBLIC_` to be exposed to the browser. See [Environment variables not working (Next.JS 9.4.4)](https://stackoverflow.com/questions/62386582/environment-variables-not-working-next-js-9-4-4). – juliomalves Sep 05 '22 at 15:04

0 Answers0