skip to Main Content

Using: Next.js 14+ App Router

I am following this guide: https://wpengine.com/builders/next-js-13-and-wpgraphql-in-headless-wordpress/ to improve my skillset with Next.js/React.js.

My issue is that when I use their code to fetch, I receive a fetch failed error. Though, if I make it a client components and use useEffect and useState, the fetch succeeds and retrieves the data.

Here is what I mean, instead of this code:

const posts = await getPosts();

I use this:

  const [posts, setPosts] = useState([]);

  useEffect(() => {
    async function fetchPosts(){
      const fetchedPosts = await getPosts();
      setData(fetchedPosts);
    }

    fetchPosts()
  }, [posts]);

But I do not want to be using useEffect(()), as I want the server to cache the data fetched as well.

Any thoughts?

Edit: Made an error on which code worked. To reiterate, I do not want to be using useEffect to fetch, I know that sounds incorrect since we don’t want our components to fetch each render, but I’m following the guide in the link above. And looking through tutorials online, especially on Next.js docs, they don’t use useEffect as well.

2

Answers


  1. It seems like the problem might be with your use of the await keyword inside the useEffect hook.

    Dont do that. You can refactor the code like this.

    useEffect(() => {
      const fetchPosts = async () => {
        const posts = await getPosts();
        setPosts(posts);
      };
    
      fetchPosts();
    }, []);
    
    Login or Signup to reply.
  2. If you’re using the app router and react server components, you can mark the component function as async and use the the await right in the root of your component, as long as it isn’t a client component.

    Try something like this:

    const MyComponent = async (myPropStuff: MyPropStuffType) => {
        const posts = await fetch(...)
    }
    

    But again, this only works if that component isn’t a client component and neither are any of it’s parents. That means no useEffect or useState at all.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search