I can't figure out how to call upon Datastore2 properly

I’m having trouble using Datastore2. I can save the data and load it properly but this table is supposed to update whenever the player joins and it sometimes runs and sometimes doesn’t. It seems like too advanced of an issue for my level yet so I was wondering if I could get help. Thank you!

Script:

local Player = game.Players.LocalPlayer

–Services
local ReplicatedStorage = game:GetService(“ReplicatedStorage”)
local HttpService = game:GetService(“HttpService”)

–Locals
local InventoryGui = script.Parent
local Container = InventoryGui:WaitForChild(“Container”)
local Template = InventoryGui:WaitForChild(“Template”)

local DataFolder = ReplicatedStorage.ReplicatedData:WaitForChild(Player.UserId)

–Bind to StringValue.Changed
local encodedData = function(encodedData)
–Decode JSONArray
local dataTable = HttpService:JSONDecode(encodedData)

--Iterate through all entires
for itemName, amount in pairs(dataTable) do
	--Find label in container
	local label = Container:FindFirstChild(itemName)
	--If label doesn't exist, clone
	if (not label) then
		label = Template:Clone()
		label.Name = itemName
		label.Parent = Container
			label.Visible = true
	end	
	
	--Update text	
	local itemlist = game.ReplicatedStorage.Items:GetChildren()
	local items = {}
	for i=1,#itemlist do
		if itemlist[i].Name == itemName then
			if itemlist[i]:IsA("Tool") then
				print("hi")
				local itemimage = itemlist[i].TextureId
				label.Image = itemimage
			else
				local itemimage = itemlist[i].Image.Value
				label.Image = itemimage
			end
		end
	end
end

end

DataFolder.Inventory.Changed:Connect(encodedData)
game.Players.PlayerAdded:Connect(encodedData)

2 Likes