Is this the right way to use Update Async to save data?

I’m not sure if this is the right way to use update async to save data, but knowing me it isn’t lol.

--// [Data Store] \\-- 
local DSS = game:GetService("DataStoreService")
local MoneyDataStore = DSS:GetDataStore("Money")
----------------------

game.Players.PlayerAdded:Connect(function(player)
	local MoneyKey = player.UserId .. "-Money"
	local MoneyData = MoneyDataStore:GetAsync(MoneyKey)
	local Money, leaderstats = Instance.new("IntValue"), Instance.new("Folder")
	Money.Name = "Money"
	leaderstats.Name = "leaderstats"
	Money.Parent = leaderstats
	leaderstats.Parent = player
	local success, errormessage = pcall(function()
	end)
	if success then
		print("Success")
		if MoneyData then
			print("Data Found")
			Money.Value = MoneyData
		else
			print("No data Found")
			Money.Value = 5
		end
	elseif errormessage then
		print(errormessage)
	end
end)

game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function(player)
	player.leaderstats.Money.Value = player.leaderstats.Money.Value + 20
end)

game.Players.PlayerRemoving:Connect(function(player)
	local MoneyKey = (player.UserId .. "-Money")
	local success, errormessage = pcall(function()
		MoneyDataStore:UpdateAsync(MoneyKey, function(oldValue)
			print("Update Async")
			local MoneyValue = player.leaderstats.Money.Value
			local newValue = oldValue or 0
			newValue = MoneyValue
			return newValue
		end)
	end)
	if success then
		print("Success")
	elseif errormessage then
		print(errormessage)
	end
end)

I don’t really see the purpose of using UpdateAsync if you do nothing with the old value. Better off just using SetAsync if you don’t need to know the old value at all.

Most people use UpdateAsync when they have a table and want to update specific keys while keeping any other data in the table as it was. Or when incrementing or decrementing a numerical value. Or when there is some sort of check, for example if you have XP which can never go down, you might use UpdateAsync to return the largest of the old and new values, math.max(old, new).

1 Like