Next.js Discord

Discord Forum

Fetch and Server actions

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
Hello guys I am new in nextjs and I am really confused with the proper way to fetch data of my API, I asked this question before but I did not elaborate properly, as long as I understand there are 2 options, either using "fetch" or using a function stored in any file of your project, I would like to know when to use which and why, I am attaching pictures of the same thing working with the 2 different approaches, first 2 images are with the fetch, and the last 2 are with the server action:

13 Replies

Hi!

My 2 cents:
1. I use react-query or equivalent when I don't need a direct interaction by the user or if the code is too complicated to handle otherwise. EG : infinite scrolling in a table / search page
2. I use API when I need a stable URL across deployment to be accessible but not only by my app.
3. I don't use server action for get because you can just pass a promise instead. Server action = mutation

give a promise to a client component example:

async function MyServerComponent() {
  const promiseData = getMyData();

  return (
    <Suspense fallback={<Spinner />}>
      <MyClientComponent promiseData={promiseData} />
    </Suspense>
  );
}


"use client";
import { useSuspenseQuery } from "@tanstack/react-query";

export function MyClientComponent({promiseData}) {
  const {data} = useSuspenseQuery({
    queryKey: ["my unique key"]
    queryFn: () => promiseData
  });

  return <div>{data}</div>
}
Sun bearOP
Thank you so much, so basically, for GET requests I should use fetch and server actions for mutating the data lets say a POST request right?
Exactly
Take time to check react-query / swr to fetch instead of a use effect
This will simplify your maintenance in the future
@Julienng live example: https://codesandbox.io/p/devbox/wispy-butterfly-dcddqw
folder p1: server only
folder p2: pass a promise as a props + react-query
folder p3: api + react-query
Sun bearOP
Why is that difference, I mean what are the advantages of using fetch for GET requests and server actions for POST requests?
Here an example:
function MyComponent() {
  const [data, setData] = useState(null);
  useEffect(() => {
    fetchData().then(data => setData(data))
  }, [])

  return <div>{data}</div>
}


This implementation is naive in the following way:
- fetch X times if my component is instanciated X times
- doesn't handle error
- doesn't handle loading state
- doesn't handle race condition: the slowest request is the one that won
- doesn't handle cancel request on re-render
- doesn't share the same data between instances of the same component
- (probably more)

const [data, setData] = useState(null);
const [state, setState] = useState<"idle" | "loading"| "error">("idle");
useEffect(() => {
  flushSync(() => setState("loading"));
  let isValid = true;
  fetchData()
    .then(data => isValid && setData(data))
    .then(() => isValid && setState("idle"))
    .catch(() => isValid && setState("error")); // TODO: catch the error

  return () => {
   isValid = false;
  }
}, [])
react-query / swr handle all of that for you (and more)
Sun bearOP
Thank you so much, I will read more about react-query and swr
Don't forget to mark the question as resolved

Happy hacking 🙂
Sun bearOP
How do I do that?