Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you use :UpdateAsync()? (for datastores)

I've heard that this is better than :SetAsync() and that it considers the old data instead of just replacing it.

1 answer

✓ Accepted answer

UpdateAsync wiki. Yes you are right, it considers the old data and you should really use it instead of SetAsync, i managed to loose my data 7 times with this nasty.

The way you use UpdateAsync is that you check whether the data you want to save is valid for saving and if it is not you can just not save it (Better than overriding the whole data).

In my case i have a variable called TotalTimesSaved, it's a value that represents how much time have user saved their data, since i have autosave, the number will constantly rise and when i use UpdateAsync i always check if the old TimesDataSaved is lower than the new one, this way i can be sure that my data won't be lost.

The first argument that this function returns is the previous data and it saves what you return, if you return nil, it won't save any data and won't override anything, here is example of how i use it:

local NewData = {
	TimesSaved = 0,
}

local function Update(PreviousData)
	if (PreviousData) then
		local PreviousTimesSaved = PreviousData.TimesSaved

		--/If previous times data does not exist or is higher than
		--\new TimesSaved then something is wrong with the data
		--\and it will return nil which won't ovverride anything
		if not (PreviousTimesSaved) or(PreviousTimesSaved >= NewData.TimesSaved) then
			return nil
		end
	end
	
	NewData.TimesSaved += 1

	--/This will be saved because notthing returned which means
	--\the data is ok!
	return NewData
end

local Saved = DataStore:UpdateAsync('MyKey', Update)

It returns the data that was saved if i am sure, which means if it did not save anything you can do

local Saved = DataStore:UpdateAsync('MyKey', Update)

if not (Saved) then
	print 'no data saved because something went wrong'
else
	print('This data was saved:', Saved)
end

Also make sure to use it with Pcalls (Protected Calls), UpdateAsync can fail too!

Source > UpdateAsync

This discussion is preserved as it was. New answers, comments, and votes are closed.