Values duplicating (Data save)

Ok, so I made a data save for my redeemed codes, it practically saves the values and everything works fine, but when I tested it out multiply times, I saw that the values duplicated (I have no idea how that happened), I tried to debug it by printing the table, re-scripting it, etc. but nothing worked and the values still duplicate.

local DTS = game:GetService("DataStoreService")
local RedeemedCodesStore = DTS:GetDataStore("RedeemedCodes")
local Codes = {}


game.Players.PlayerAdded:Connect(function(plr)
	local RedeemedCodes = plr:WaitForChild("AlreadyRedeemedCodes")
	local Key = "KEy_"..plr.UserId
	local Data
	
	local success, errormessage = pcall(function()
		Data = RedeemedCodesStore:GetAsync(Key)
	end)
	
	
	if success then
		if Data ~= nil then
		print("Work!")
		for i = 1, #Data do
			local temp = Instance.new("StringValue")
			temp.Parent = RedeemedCodes
			temp.Name = Data[i]
			temp.Value = Data[i]
			wait()
end
		else
	print("Work, user new!")
end
	else
	print(errormessage)
end
end)




game.Players.PlayerRemoving:Connect(function(plr)
	local RedeemedCodes = plr:WaitForChild("AlreadyRedeemedCodes")
	local Key = "KEy_"..plr.UserId
	local Data
	
	for i, v in pairs(RedeemedCodes:GetChildren()) do
		if v:IsA("StringValue") then
			table.insert(Codes, v.Value)
			wait()
			end
		end
		local success, errormessage = pcall(function()
			Data = RedeemedCodesStore:SetAsync(Key, Codes)
		end)
		
		if success then
			print("work")
		else
				print(errormessage)
		end
		print(unpack(Codes))
end)







game:BindToClose(function()
	local PlayersLeft = game.Players:GetPlayers()
	for i, plr in pairs(PlayersLeft) do
	local RedeemedCodes = plr:WaitForChild("AlreadyRedeemedCodes")
	local Key = "KEy_"..plr.UserId
	local Data
	
	for i, v in pairs(RedeemedCodes:GetChildren()) do
		if v:IsA("StringValue") then
			table.insert(Codes, v.Value)
			wait()
			end
		end
		local success, errormessage = pcall(function()
			Data = RedeemedCodesStore:SetAsync(Key, Codes)
		end)
		
		if success then
			print("work")
		else
				print(errormessage)
		end
	end
end)







while wait(5) do 
	print(unpack(Codes))
end

From what I can tell the issue might be that you’re saving the players data twice. Once on player removing and once on bind to close. What I would recommend is just having a table set up something like this:

local Saved = {}

—In the save function
if Saved[player.Name] then return end
Saved[player.Name] = true

In addition, the way you are saving the players data might also work better as a dictionary rather than an array. Currently you have table.insert(Codes, v.Value) but it might make more sense to do Codes[v.Value] = true that way you can’t have multiple of the same code in your datastore.

Alright, I will try that out and tell you if that works.

Alright, it is working fine now, thank you.

1 Like