Adding .env file to access to all components and pages in Next JS 14

NEXT_PUBLIC_WORDPRESS_GRAPHQL_ENDPOINT=https://jjrevamp.jjecom.com/graphql/

To access this URL in all pages we need to add

NEXT_PUBLIC_SOMETHING

THis will enable to call the URL in any pages

Calling the posts using GRaphQL API

onst client = new ApolloClient({
  uri: process.env.NEXT_PUBLIC_WORDPRESS_GRAPHQL_ENDPOINT,
  cache: new InMemoryCache()
});
const graphqlEndpoint = process.env.NEXT_PUBLIC_WORDPRESS_GRAPHQL_ENDPOINT;
console.log("Graph URL", graphqlEndpoint);
const FetchPosts = () => {
    const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
  
    useEffect(() => {
      const fetchPosts = async () => {
        try {
          console.log("URL" ,client.uri);



          const response = await fetch(graphqlEndpoint, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              query: `
                query FetchPosts {
                  posts {
                    edges {
                      node {
                        id
                        title
                        content
                        featuredImage {
                          node {
                            id
                          }
                        }
                        slug
                      }
                    }
                  }
                }
              `,
            }),
          });
  
          if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
          }
  
          const data = await response.json();
          setPosts(data.data.posts.edges.map(edge => edge.node));
          setLoading(false);
        } catch (error) {
          setError(error);
          setLoading(false);
        }
      };
  
      fetchPosts();
    }, []);

Leave a comment

Your email address will not be published. Required fields are marked *