π Basics of calling an API
The apiRequest
function is used to send data to the server or retrieve something from the database. It's your go-to method when performing actions like saving users, fetching records, or processing logic server-side.
π Example Structure
src/
dashboard/
page.tsx
_components/
_functions/
_api/
saveUser.ts
deleteUser.ts
home/
page.tsx
β The folder name must end in
api
, such as_api
or_dashboardApi
.π« Api routes are scoped to their route folder. In the example above,
saveUser
can be called only from/dashboard
. It won't be available on/home
or other pages.π‘We recommend starting folder names with an underscore (
_
) to indicate that itβs a non-route folder, making the project structure easier to read for other developers.
This structure allows you to use the same API name in different places (e.g. saveUser
on /dashboard
and /home
), without any conflict.
π Where You Can and Can't Call
β Can call
apiRequest({ name: "refreshData", data: { name: 'Mike' } })
from inside thepage.tsx
or components under the same route (e.g./dashboard
)β Cannot call a api route that belongs to a different page route (e.g., trying to call
/home/_api/refreshData
from/dashboard
)
βοΈ How to use apiRequest
Since apiRequest
returns a Promise
, you need to call it inside an async
function.
β You cannot call it directly in the top-level body of a React component.
β
Use it like this inside a useEffect
handler:
You can find more advanced usage and patterns on the next page.
Last updated