How to Properly use UpdateAsync()

Hi, I have a problem, I’m currently making a data store for saving data. I’m testing to see if it works. This data store utilizes UpdateAsync(). I have read various articles on UpdateAsync(), none have really showed me how exactly to use it to save data or to increment it.

Here’s my code, should be pretty easy to understand:

local DataStoreServ = game:GetService("DataStoreService")
local Ds = DataStoreServ:GetDataStore("DataForAllLeaderstats")


local function PlayerAdded(Player)
	local Key = "Player-"..Player.UserId
	local Folder = Instance.new('Folder')
	Folder.Parent = Player
	Folder.Name = "leaderstats"
	local Coins = Instance.new("IntValue")
	Coins.Name = "Coins"
	Coins.Value = 0
	Coins.Parent = Folder
	local Exp =  Instance.new("IntValue")
	Exp.Name = "Exp"
	Exp.Parent = Folder
	Exp.Value = 0
	local success, err = pcall(function()
		 Data = Ds:GetAsync(Key)
	end)
	if Data then
		print("Found Data")
		print(Data)
	else
		for i,v in pairs(Folder:GetChildren()) do
			v.Value = 0
		end
	end
end

local function OnPlayerLeft(Player)
	local Key = "Player-"..Player.UserId
	local success, err = pcall(function()
		Ds:UpdateAsync(Key, function(OldValue)
			-- I don't know what exactly to put here.
			end)
		end)
end
game.Players.PlayerAdded:Connect(PlayerAdded)
game.Players.PlayerRemoving:Connect(OnPlayerLeft)

What exactly would I put in the UpdateAsync() function for it to save the data?

Any articles, posts or pieces of code, would be greatly appreciated! :slightly_smiling_face:

1 Like
		Enum.DataStoreRequestType.UpdateAsync), ignorethis, function()
			return cashValue
		end)
3 Likes

Well all you really have to do is:
Might be complex but still:

Ds:UpdateAsync(Key, function(OldValue)
    return yourData
end)

I know it’s hard but yeah.
Some people have measures to prevent the same data from being saved again, not sure about them.


Source: GlobalDataStore:UpdateAsync (roblox.com)

3 Likes

What would yourdata be? Can you pelase show me an example?

Values that would be in, for example, leaderstats. You can save those values.

--yourData would be something like Values, just a Data dictionary
local Values = {
    Coins = Player.Leaderstats.Coins.Value
}

Ds:UpdateAsync(Key, function(OldValue)
    return Values
end)
3 Likes

Alright, I’ll try this. Also, one more questions. What is DataId? I seen people do this:

Ds:UpdateAsync(Key, function(OldValue)
    if OldValue.DataId then
end
end)

Oh, its just the ID for the dictionary. I think people use it to avoid saving the same old data. Not sure.

Oh, how would I create a DataId then for the “yourData”?

local Data = {
    DataId = 0,
    --rest of your data
}

And that’s how.

Alright, thank you! I’ll try everything you just told me.

1 Like