Data not saving only when player removes

local DSS = game:GetService("DataStoreService")

local PlayerData = DSS:GetDataStore("PlayerData1")
local GlobalData = DSS:GetDataStore("GlobalData1")

local Pops = {}

game.Players.PlayerRemoving:Connect(function(plr)
	pcall(function()
	
		print(PlayerData:GetAsync(plr.UserId.."-coins"))
		PlayerData:SetAsync(plr.UserId.."-coins", plr.leaderstats.Coins.Value)
		Pops = {}
		for i,v in pairs(plr.PlayerGui.TestGui.CollectionGui.ScrollingFrame:GetChildren()) do
			if v:IsA("ImageButton") then
				table.insert(Pops, v.Name)
			end
		end
		PlayerData:SetAsync(plr.UserId.."-pops", Pops)
		
	end)
	
end)

I’m not sure what I did wrong here, I have been doing datastore for a while now…

When a player leaves the server might have closed before the data was saved

Try this:

--//Services
local Players = game:GetService("Players")
local DSS = game:GetService("DataStoreService")

--//Variables
local PlayerData = DSS:GetDataStore("PlayerData1")
local GlobalData = DSS:GetDataStore("GlobalData1")

--//Tables
local Pops = {}

--//Functions
local function SaveData(player)
	local success, errorMessage = pcall(function()
		PlayerData:SetAsync(player.UserId .."-coins", player.leaderstats.Coins.Value)

		Pops = {}

		for i, child in ipairs(player.PlayerGui.TestGui.CollectionGui.ScrollingFrame:GetChildren()) do
			if child:IsA("ImageButton") then
				table.insert(Pops, child.Name)
			end
		end

		PlayerData:SetAsync(player.UserId .."-pops", Pops)
	end)

	if not success then
		warn(errorMessage)
	end
end

Players.PlayerRemoving:Connect(function(player)
	SaveData(player)
end)

game:BindToClose(function()
	for i, player in ipairs(Players:GetPlayers()) do
		task.spawn(function()
			SaveData(player)
		end)
	end
end)

Thanks you so much! I really appreciate it :grin: