How to improve Inventory

So i did a Inventory Datastore script
and i feel like it can bug out…

I need some improvents bcs i had problems with the datastore being

local DataStore = game:GetService("DataStoreService")
local InventoryD = DataStore:GetDataStore("Inv")
local HttpS = game:GetService("HttpService")
local Inv = DataStore:GetDataStore("InvT")
local InvDied = game.ReplicatedStorage.Inventory.Events:WaitForChild("InvDied")

local R_INV = game.ReplicatedStorage.Inventory.Events:WaitForChild("Recieve_INV")
local Send_INV = game.ReplicatedStorage.Inventory.Events:WaitForChild("Send_INV")

local Inventory = { -- Example Player Inventory

}


InvDied.OnServerEvent:Connect(function(plr)
	print("e")
	local folder = Instance.new("Folder",plr)
	folder.Name = "Invent"


	local success,errorMessage = pcall(function()
		local data = Inv:GetAsync(plr.UserId)
		
		if data == nil then
			Inventory = {}
		else	
			Inventory = data
		end
		
	end)
	
	
	
	if success then
		print("Data successfully loaded!")
	end
	if errorMessage then
		warn(errorMessage)
	end

	Send_INV:FireClient(plr, Inventory)
	game.Players.PlayerRemoving:Connect(function(plr)
		Inv:SetAsync(plr.UserId, Inventory)
	end)

	game:BindToClose(function()
		for i,plr in pairs(game.Players:GetPlayers()) do
			Inv:SetAsync(plr.UserId, Inventory)
		end
	end)
end)


R_INV.OnServerEvent:Connect(function(plr, ID) --inserts item

	local success,errorMessage = pcall(function()
		local data = Inv:GetAsync(plr.UserId)
		if data == nil then
			Inventory = {}
		else	
			Inventory = data
		end
	end)
	
	table.insert(Inventory, ID)
	Inv:SetAsync(plr.UserId, Inventory)

end)

InvDied.OnServerEvent:Connect(function(plr)
	local success,errorMessage = pcall(function()
		local data = Inv:GetAsync(plr.UserId)
		if data == nil then
			Inventory = {}
		else	
			Inventory = data
		end
	end)
	Send_INV:FireClient(plr, Inventory)
	
end)