fetchNui
Last updated
Last updated
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.
import { fetchNui } from "@yankes/fivem-react/utils";
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.
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.
const response = fetchNui("send-data", { newValue: "value" })
.then(() => console.log("Data submitted successfully"))
.catch((error) => console.error("Failed to submit data", error));
RegisterNuiCallback("send-data", function (data, cb)
print(data.newValue)
cb(true)
end)
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 the fetch
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 a POST
request to the URL constructed by the getResourceUrl
utility. It passes the body
(if provided) as the request payload by stringifying it into JSON format.
fetch
Availability Check: If fetch
is not available in the environment (for instance, in a server-side context), it throws an error indicating that fetch
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.
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.