javascripttypesluacallbackfivem

Why FiveM script client callback does not receive the right variable type?


I am creating a FiveM script and I need to get the source citizenId and I am having a problem with what my client callback function receives from a server event. The server event return a string and I know it for a fact because I tried to print the variable and it's type in the console and it was correct. But the second it goes to the function in which it got returned, it's not a string anymore, it's an "object".

For minimal reproduction,

Here is the JS script that call my client callback on a button click (Working): html/script.js

const createOrg = () =>{
    var orgName = document.getElementById("neworg-name-input").value;
    fetch(`https://${GetParentResourceName()}/orgcreateCb`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=UTF-8',
        },
        body: JSON.stringify({
            organizationName: orgName,
        })
    }).then(resp => resp.json()).then(resp => console.log(resp));
    //console.log(orgName);
};

Here is the server event that return the string (Working): server/main.lua

RegisterServerEvent('getPlayerCitizenId')
AddEventHandler('getPlayerCitizenId', function(cb)
    local currentCitizenId = QBCore.Functions.GetPlayer(source).PlayerData.citizenid
    cb(tostring(currentCitizenId))
end)

Here is the client callback that need what the server event returns (Not working): client/main.lua

RegisterNUICallback("orgcreateCb", function(data, cb)
    TriggerServerEvent('getPlayerCitizenId', function(citizenId)
        print('Citizen ID:', citizenId)
    end)
end)

On the print I get -> "SCRIPT ERROR: error object is not a string"


Solution

  • You can just use QBCore.Functions.GetPlayerData().citizenid client-side, to get the citizenid of the player