Dtoring Stats with Data Store

So my data is not storing and i don’t know why. I used the same script in every game i make but the game im currently making is not storing the data.

local DataStoreService = game:GetService("DataStoreService")
local ds = DataStoreService:GetDataStore("Clicks")

game.Players.PlayerAdded:Connect(function(player)
	if player then
		local leaderstats = Instance.new("Folder")
		leaderstats.Name = "leaderstats"
		leaderstats.Parent = player

		--Points For Finishing Without Dying
		local clicks = Instance.new("IntValue")
	    clicks.Name = "Clicks"
		clicks.Value = 0
		clicks.Parent = leaderstats

		local data
		local success, errormessage = pcall(function()
			data = ds:GetAsync(player.UserId.."Clicks")
		end)

		if success then
			clicks.Value = data
		else
			print("There is an error")
			warn(errormessage)
		end
	end
end)

game:GetService('Players').PlayerRemoving:Connect(function(player)

	local success, errormessage = pcall(function()
		ds:SetAsync(player.UserId.."Clicks",player.leaderstats.Clicks.Value)
	end)

	if success then
		print("Player Data has been saved!")
	else
		print("There is a error")
		warn(errormessage)
	end
end)

Is the value of the clicks stat being correctly changed on the server?

If you’re testing this in studio then PlayerRemoving doesn’t always fire, if you’d like some code to execute when a server shuts down take a look at the following.

https://developer.roblox.com/en-us/api-reference/function/DataModel/BindToClose

game:BindToClose(function()
	for _, player in ipairs(game:GetService('Players'):GetPlayers()) do
		local success, errormessage = pcall(function()
			ds:SetAsync(player.UserId.."Clicks",player.leaderstats.Clicks.Value)
		end)
		
		if success then
			print("Player Data has been saved!")
		else
			print("There is a error")
			warn(errormessage)
		end
	end
end)

i think i found the problem. thanks for sharing.

What was the problem? If you don’t mind sharing (it may help others who come across this thread).