How do I use UpdateAsync()?

Hi, I’m working on my first game and I added a data store which store items and values but my data store keeps losing data and I’m learning how to use UpdateAsycn(), I searched youtube for a tutorial but there’s none and a search the dev hub but I can’t understand it. can anyone simply explain UpdateAsync()?

Heres the Devhub code explained.

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) -- The 'oldValue' is what is currently stored in the datastore.
			local newValue = oldValue or 0 -- If the oldValue is nil it automatically becomes 0
			newValue = newValue + 50 -- Adds 50 to the value
			return newValue -- Returns the updated value to the datastore where the datastore then changes the selected datastore keys value to the new value
		end)
	end)
end)
3 Likes

but can you tell me the difference between SetAsync() and UpdateAsync() is?

UpdateAsync basically has a parameter of the previously saved value in the datastore. You can then use that value to increment, let’s say, cash by a certain value. However, SetAsync simply overwrites that value.

so how do you prevent data lose with UpdateAsync()?

UpdateAsync won’t necessarily prevent data loss. It seems like you’re coming close to an XY Problem; instead of trying to switch the function you’re using you should debug your own code first for a source of the issue. It’s important to share what you have to work with in a thread so that advice can be offered based on what you’ve already got. Can you share the code that is not working for you?

1 Like