Progress deletes after making a new boolValue in a folder that is inside a player with datastore

Hello everyone, hope you guys have a good day, I’ve made a code that saves my boolValue’s that is in a folder that is inside a player, script works fine and everything is working, one thing though is when I add a new boolValue, the data is deleted.

Here’s my code:

local players=game:GetService("Players")
local datastore = game:GetService("DataStoreService")
local saving = datastore:GetDataStore("TrophiesSaving")
local Saving = {}
local HTTPService = game:GetService("HttpService")

players.PlayerAdded:Connect(function(p)
	if p:FindFirstChild("TrophiesFolder") then
		print("Found folder")
		
		local newData = saving:GetAsync(p.UserId)
		local data
		local success,errorr = pcall(function()
			data = HTTPService:JSONDecode(newData) 
		end)
		if success then
			print(data)
			for i,v in pairs(p:FindFirstChild("TrophiesFolder"):GetDescendants()) do
				if v:IsA("BoolValue") then
					v.Value = data[i]
					print(data)
				end
			end
		else
			print(errorr)
		end
	end
end)

players.PlayerRemoving:Connect(function(p)
	if p:FindFirstChild("TrophiesFolder") then
		for i,v in pairs(p:FindFirstChild("TrophiesFolder"):GetDescendants()) do
			if v:IsA("BoolValue") then
				table.insert(Saving, v.Value)
			end
		end
		print(Saving)
		local Encoded = HTTPService:JSONEncode(Saving)
		saving:SetAsync(p.UserId, Encoded)
	end
end)

Here’s the folder located:
Screenshot 2024-03-30 135330

Any help is appreciated!

1 Like

hi, I noticed that due to how you’re saving and loading the data, the data will delete due to incorrect order detected.

When you save the data, you’re storing the BoolValues in an array (the ‘Saving’ table), which means the order of the BoolValues is important. If you add a new Boolvalue, the order changes, and when you load the data, it tries to apply the saved values to the BoolValues in the new order, which can make that happen

To fix this, you should save the data as a table with keys corresponding to the names of the BoolValues, so each value is loaded back into the correct BoolValue regardless of order

An example I made

-- When saving:
local saveData = {}
for i,v in pairs(p:FindFirstChild("TrophiesFolder"):GetDescendants()) do
  if v:IsA("BoolValue") then
    saveData[v.Name] = v.Value
  end
end
local encoded = HTTPService:JSONEncode(saveData)
saving:SetAsync(p.UserId, encoded)

-- When loading:
local newData = saving:GetAsync(p.UserId)
if newData then
  local data = HTTPService:JSONDecode(newData)
  for i,v in pairs(p:FindFirstChild("TrophiesFolder"):GetDescendants()) do
    if v:IsA("BoolValue") and data[v.Name] ~= nil then
      v.Value = data[v.Name]
    end
  end
end

:smile:

Thank you so much, the code worked!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.