fetchNui
Overview
The fetchNui
utility function is used to send HTTP POST
requests to a specified endpoint. It handles making network requests to a resource URL, which is determined dynamically based on the environment (production or development). This utility is often used in the context of sending data to the NUI (Native User Interface) layer in FiveM or similar environments.
Put simply, you can send nui callbacks with this utility.
Additionally, this utility is utilized in the useNuiQuery
and useNuiMutation
hooks to handle network requests within React components.
Usage
Importing the Utility
Parameters
endpoint
string
The URL endpoint to which the POST
request will be made.
body
FetchNuiBody
(optional)
The request body that will be sent with the POST
request. It can be of various types such as a string
, number
, boolean
, an Array
, or an Object
. If not provided, the request will be sent without a body.
Return Value
The function returns a Promise
which resolves when the request completes. If the environment is not in production, it will immediately resolve without making any network request. In a production environment, it will make a POST
request to the constructed URL.
Example
ReactJS
LUA
How It Works
In non-production (development) environments: The function returns a resolved promise without sending a request.
In production environments: The function sends a
POST
request to the provided endpoint URL and returns the result of thefetch
call.Non-Production Mode: If the environment is not production (i.e.,
process.env.NODE_ENV !== "production"
), the function immediately returns a resolved promise without sending any request. This is useful for avoiding unnecessary network calls during development.Production Mode: If in production, the function uses the
fetch
API to make aPOST
request to the URL constructed by thegetResourceUrl
utility. It passes thebody
(if provided) as the request payload by stringifying it into JSON format.fetch
Availability Check: Iffetch
is not available in the environment (for instance, in a server-side context), it throws an error indicating thatfetch
is not defined.The function is primarily used to communicate with the NUI layer, which typically involves sending requests to endpoints associated with the user interface or server-side logic in a game server like FiveM.
Conclusion
The fetchNui
utility simplifies the process of sending POST
requests in a production environment and skipping unnecessary requests in development. It is a useful tool for managing communication between the client and NUI layers, especially in environments like FiveM, and works seamlessly with hooks like useNuiQuery
and useNuiMutation
for React-based interactions.
Last updated