How do i convert the setasync() to updatsync()

How do i convert this to update async that save new value

local DataStoreService = game:GetService("DataStoreService") -- DataStore Variable
local myDataStore = DataStoreService:GetDataStore("myDataStore") 

game.Players.PlayerAdded:Connect(function(player) 
	local leaderstats = Instance.new("Folder",player) 
	leaderstats.Name = "leaderstats" 
	
	local Coins = Instance.new("IntValue", leaderstats)
	Coins.Name = "Coins" 
	Coins.Value = 0 
	
	local playerUserId = "Player_"..player.UserId 
	
	--Load Data
	local data
	local sucess, errormessage = pcall(function() 
		wait(0.05)
		data = myDataStore:GetAsync(playerUserId) 
	end)
	
	Coins.Value = data
	
	if sucess then 
		
		data = myDataStore:GetAsync(playerUserId)
		
	elseif not sucess then
		
		player:Kick("Your coins data dont load properly try to rejoin.")
	end
	
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	wait()
	local playerUserId = "Player_"..player.UserId 
	
	local data = player.leaderstats.Coins.Value
	
	local sucess, errormessage = pcall(function()
		wait()
		myDataStore:SetAsync(playerUserId, data)
	end)
	
	if sucess then
		wait()

	else
		wait()
		warn(playerUserId.. " There was an error while saving the data of coins.")
		wait()
		myDataStore:SetAync(playerUserId, data)
	end
end)

I snatched the example from this.

local pointsDataStore = game:GetService("DataStoreService"):GetDataStore("Points")
 
game.Players.PlayerAdded:Connect(function(player)
	local playerKey = "Player_" .. player.UserId
	-- Give 50 points to players each time they visit
	local success, err = pcall(function()
		pointsDataStore:UpdateAsync(playerKey, function(oldValue)
			local newValue = oldValue or 0
			newValue = newValue + 50
			return newValue
		end)
	end)
end)
2 Likes

Can you help me i dont really know how to use updateasync() correctly

there, read

It’s very easy to implement.

game.Players.PlayerRemoving:Connect(function(player)
	wait()
	local playerUserId = "Player_"..player.UserId 
	
	local data = player.leaderstats.Coins.Value
	
	local success, errormessage = pcall(function()
		wait()
		myDataStore:UpdateAsync(playerUserId, function(oldValue)
			local newValue = data or oldValue or 0
			return newValue
		end)
	end)
	
	if success then
		--
	else
		warn(playerUserId.. " There was an error while saving the data of coins.")
	end
end)

You can rewrite the logic on how you want to apply this newValue without accidentally losing the data.

1 Like