Help needed with databases

The general rule is to always use UpdateAsync() instead of SetAsync() when saving your data because SetAsync() can be hazardous. However there are some developers that use SetAsync() to save there data. DataStore2 is a great example of this and I think the reason why it does this is because it is never overriding and previous saved data. I will need some clarification on that though.

SetAsync() doesn’t take into account any previous saved data and should only be used when you need to force data. From my understanding it is fine to use SetAsync() when you don’t have any saved data for the player because you are not overriding any previous saved data.

You can use UpdateAsync() even when you don’t have any saved data. This is because it returns the current saved value and then you can check if the current value is nil and then return default data. Here is a tuturial on why you should be using UpdateAsync: Stop using SetAsync() to save player data. Then here is some horrible code that I just made to show how you can use UpdateAsync() even when you don’t have any saved data:

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("Test")

local DefultValue = 20

game.Players.PlayerAdded:Connect(function(Player)
	local Success, Error = pcall(function()
		DataStore:UpdateAsync(tostring(Player.UserId), function(CurrentValue)
			if CurrentValue == nil then
				print("No data exists")
				return DefultValue
			else
				print("Data Exists")
				return CurrentValue + 4
			end
		end)
	end)
	
	if not Success then
		warn(Error)
	end
end)

Please don’t use this code as it is because it is missing a lot of stuff from it. For example it doesn’t first check if the player doesn’t have any saved data.

1 Like