DataStoreService Not Saving On Player Leave

Hello, I have an issue, i am trying to save a dictionary but it is not saving, i tried saving it manually it worked but it wont work when the player is leaving

Players.PlayerRemoving:Connect(function(Player:Player)
	local USERIDstring = tostring(Player.UserId)
	local Data = SessionData:WaitForChild(tostring(Player.UserId))
	local TD = {}

	local StarterGuiPlayer = Player:WaitForChild("PlayerGui")
	local ToDoGui = StarterGuiPlayer:WaitForChild("ScreenGui")["To-Do"]

	for i, f:Frame in ipairs(ToDoGui.ScrollingFrame:GetChildren()) do
		if f.Name~="toclone" and f.Name~="UIListLayout" and f:IsA("Frame") then
			local checked = f.Check.Image=='rbxassetid://16805854289'
			local Text:TextBox = f.TextBox
			--print(f.Name,Text)
			if Text.Text~="" then
				TD[Text.Text]=checked
				--print(Text,":",checked)
			end
		end
	end	
	TD=HttpService:JSONEncode(TD)
	print(TD)
	To_DoData:SetAsync(Player.UserId, TD)
	

	Data:Destroy()
end)

Also Just Wanna Say I researched and i didnt understand

When the game is closing, the data is not saved(this asynchronous operation gets cut before finish) and therefore you have to hook it to an event to this method:

1 Like

Does BindToClose() work the same as PlayerRemoving?

BindToClose() will run whenever the game’s server shuts down, not when a client’s game shuts down (e.g. a player leaves). To avoid data loss, you should save on this occasion.

local runService = game:GetService("RunService")
local players = game:GetService("Players")

local function saveAllData()
    if runService:IsStudio() then task.wait(3) return nil end
    for _, player in ipairs(players:GetPlayers()) do
        savingFunctionHere(player)
    end
    task.wait(3)
end

game:BindToClose(saveAllData)
1 Like