I have no clue what's wrong with it but here.

local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("Leaderstats")

game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder",plr)
	leaderstats.Name = "leaderstats"

	local level = Instance.new("IntValue", leaderstats)
	level.Name = "Level"
	level.Value = 1
	pcall(function()
		local function save(plr)
			local leaderstats = plr:WaitForChild("leaderstats")
			local level = leaderstats:WaitForChild("Level")

			pcall(function()
				dataStore:SetAsync(plr.UserId.. "_Level",level.Value)
			end)
		end

		game.Players.PlayerRemoving:Connect(function(plr)
			save(plr)
		end)

		game:BindToClose(function() -- runs when game closes/shutdowns
			for _, plr in pairs(game.Players:GetPlayers()) do
				save(plr)
			end
		end)

		game.Players.PlayerRemoving:Connect(function(plr)
			local leaderstats = plr:WaitForChild("leaderstats")
			local level = leaderstats:WaitForChild("Level")

			pcall(function()
				dataStore:SetAsync(plr.UserId.. "Level",level.Value)

			end)
		end)
	end)
end)