SetAsync doesn't change the data in the datastore and stops the thread during PlayerRemoved

I am using one datastore for my data. I have a “Kills” stat and a “Headshots” stat. The table changes but when the player leaves the game SetAsync just doesn’t save the data.

Here is my code:

game.Players.PlayerRemoving:Connect(function(player)
	
	print("saving data")
	print(sessionData[player.UserId])
	
	
	local setSuccess, errorMsg = pcall(function()
		print("saving1")
		StatsDS:SetAsync(player.UserId,sessionData[player.UserId]) 
-- everything under here doesn't run
		print("saving2")
	end)
	
	if not setSuccess then
		warn(errorMsg)
	else
		print("saved")
	end
	
	sessionData[player.UserId] = nil
end)

sessionData shows the correct data when printed and changes accordingly.

I’ve discovered that “saving1” is printed but “saving2” isn’t. I don’t know what I’m doing wrong. Can anyone help me?

Hmm, try converting the UserId to a string

StatsDS:SetAsync(tostring(player.UserId),sessionData[player.UserId])
1 Like

image
Doesn’t seem to work. I’ll try to use UpdateAsync instead.

Try JSONEncoding the data first (changing a table into a string)

Just remember to use JSONDecode() on it upon load

(if you don’t know how to use JSONEncode, it is this:

local HTTPService = game:GetService("HTTPService")
local ToEncode = {
    ["Apples"] = 5,
    ["Rocks"] = 51
}

local Encoded = HTTPService:JSONEncode(ToEncode)
---
local Decoded = HTTPService:JSONDecode(Encoded)
1 Like

Does this mean datastores are obsolete? If I use HTTP service then I’ll have to reset all data. Is there a way I could continue using datastores?

You use HTTPService with datastore service. DatastoreService saves and loads data, while HTTPService just changes the type of data

1 Like

So apparently SetAsync and UpdateAsync don’t even run at all. It just stops the thread.

Okay so I found out that I needed to add this:

game:BindToClose(function()
	print("saving bind to close")
	for _, player in pairs(game.Players:GetPlayers()) do
		save(player) -- does the entire saving process using setasync
	end
end)

I don’t know why, I’m guessing it’s because when I leave the game it’s only me so the server shuts down. I think the server shuts down while the player remove event is triggered, so it stops the SetAsync process. At least that’s my theory. It successfully saves every time now.

In the multiplayer setting, people are going to leave the game and data is going to be saved using the player removed event most of the time, until the last player leaves or the server is shut down. And in that case it uses game:BindToClose.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.