Fetching Data
How to fetch data in VitNode.
VitNode provides a way to fetch data from the backend using the fetcher()
function on Server Side Rendering (SSR) and fetcherClient()
on Client Side Rendering (CSR).
Fetcher (SSR)
The fetcher()
function use the next
context from the server. That means you can use it only in React Server Components (RSC) or Server Function.
The fetcher
function is just a wrapper around the fetch
function with default headers, error handles, default backend URL, and more.
Fetcher Client (CSR)
The fetcherClient()
function is used on the client-side to fetch data from the backend.
Files Upload
To upload files from the frontend, you can use the fetcherClient
function with FormData
.
Type-Safe Fetcher
The fetcher()
and fetcherClient()
functions are type-safe. You can pass the DTO object to the function by generic type.
Response
The response object is required. As an example we use the ExampleWelcomeObj
DTO object.
Body and Query
Our fetcher functions are not just type-safe for the body and query, they have also converter function to the correct format so you don't need to worry about "How to pass query into url?" or "How to pass body into fetcher using only string?".
or for query:
Param
We don't have a converter for the param, but you can pass it directly into the URL.
Revalidate data
NextJS allows you to use Revalidating data in Server Function.
Server Function
You can use the fetcher()
function in the Server Function.
Catch error
Using Server Function you can catch errors only on server side and pass them into client. As an example we will handle the PLUGIN_ALREADY_EXISTS
error to show a message in the form and toast if the error is different.
Don't handle errors directly on the client side using try/catch!
NextJS will not show the error message on the client side if you use try/catch on production. In dev mode, it will show the error message but not in production.
Debounced fetching
To avoid fetching data on every key press you can use useDebouncedCallback
from use-debounce
package.
Here is an example how to use it for search
input.