🎮
FiveM React
  • Welcome
  • Getting Started
    • Installation
  • Hooks
    • useNuiMessage
    • useVisible
    • useNuiData
  • useNuiQuery
  • useNuiMutation
  • Components
    • Visible
    • Link
  • Utils
    • isProduction
    • fetchNui
    • openUrl
    • getResourceName
Powered by GitBook
On this page
  • Overview
  • Usage
  • Importing the Hook
  • Parameters
  • Options
  • Return Value
  • Example
  • ReactJS
  • LUA
  • How It Works
  • Notes
  • Conclusion

useNuiQuery

Overview

The useNuiQuery hook sends an NUI callback to the FiveM client-side to retrieve data. It simplifies the process by allowing you to include a request body with various data types without the need for manual string conversion or parsing.

Use useNuiMutation for sending data (e.g., handle click), as it's designed for mutations, while useNuiQuery is for fetching data.

Usage

Importing the Hook

import { useNuiQuery } from "@yankes/fivem-react/hooks";

Parameters

Parameter
Type
Description
Optional

endpoint

string

Endpoint where you send NUI Callback.

options

Additional options

Options

Object contains parameters below (all parameters are optional):

Parameter
Type
Description

body

string | number | boolean | Array<unknown> | Record<string, unknown>

The body parameter contains the data sent with the NUI request, supporting various types without requiring manual string conversion.

onSuccess

(value: Response | void) ⇒ void | PromiseLike<void>

The onSuccess callback is triggered on a successful NUI response, receiving the data for further processing.

onError

(reason: unknown) ⇒ void | PromiseLike<void> | null | undefinded

The onError callback is triggered if the NUI request fails, allowing error handling or recovery actions.

onFinally

() ⇒ void | null | undefinded

The onFinally callback runs after the NUI request completes, regardless of success or failure, for cleanup or final actions.

Return Value

This hook does not return a value but automatically send a NUI Callback where you can handle diffrent states of response in options.

Example

ReactJS

import { useState } from "react";
import { useNuiQuery } from "@yankes/fivem-react/hooks";

export const MyComponent = () => {
    const [vehicles, setVehicles] = useState([]);
    const [page, setPage] = useState("los-santos");

    useNuiQuery("/garage-vehicles", {
        body: { page },
        onSuccess: await (response) => {
            const data = await response.json();
            setVehicles(data);
        },
        onError: () => alert("Something went wrong")
    });

    return (
        <div className="vehicles-container">
            {vehicles.map((vehicle) => (
                <div class="vehicle-card">
                    <h3>{vehicle.name}</h3>
                    <p>{vehicle.plate}</h3>
                </div>
            ))}
        </div>
    );
};

LUA

local testVehicles = {
    ["los-santos"] = {
        { name = "Blista", plate = "QWE123" },
        { name = "Sentinel Classic", plate = "XYZ123" }
    },
    ["sandy-shores"] = {
        { name = "Kamacho", plate = "123456" }
    },
    ["paleto-bay"] = {}
}

RegisterNUICallback("garage-vehicles", function(data, cb)
    local page = data.page

    cb(testVehicles[page] or {})
end)

How It Works

  1. The React component (MyComponent) calls useNuiQuery with the event name (/garage-vehicles) and an options object containing a body parameter ({ page }) and success/error handlers.

  2. Inside useNuiQuery, the useEffect hook triggers the fetchNui function, sending an NUI message to the FiveM client with the specified endpoint (/garage-vehicles) and request body ({ page }).

  3. On the FiveM side, the RegisterNUICallback function listens for the /garage-vehicles event. When triggered, it retrieves the requested page from the data and responds with the corresponding vehicle list from testVehicles.

  4. The response is returned to the React frontend, where the .then(options?.onSuccess) handler processes the data. The onSuccess function attempts to parse the response JSON and updates the vehicles state using setVehicles(data).

  5. The component re-renders, displaying the list of vehicles in .vehicles-container. Each vehicle is shown inside .vehicle-card, with its name and plate.

  6. If an error occurs, the onError callback triggers an alert with the message "Something went wrong."

Notes

  • The hook sends an NUI callback to the FiveM client when the endpoint or options change.

  • It uses useTransition to keep the UI responsive while processing the request.

  • The provided callbacks (onSuccess, onError, onFinally) allow flexible handling of the response lifecycle.

  • The hook automatically manages the request lifecycle without requiring manual cleanup.

  • The isPending state helps track the request status for UI updates.

Conclusion

The useNuiQuery hook provides a streamlined way to send NUI requests in a React-based FiveM environment. It abstracts the request logic, supports structured callbacks, and improves UI responsiveness with useTransition.

PrevioususeNuiDataNextuseNuiMutation

Last updated 1 month ago

Options