I need some help on on saving my data

guys to save this data properly do i need to make an bindtoclose and game players removing at the same time? i dont test it yet but i’m just curious about it

local data = game:GetService("DataStoreService")
local InventoryData = data:GetDataStore("InventorySave")




local ItemsSaved = {}

local PlayerId

local InventoryFolder 

local Jogador 

game.Players.PlayerAdded:Connect(function(player)
	
	Jogador = player
	
	PlayerId = player.UserId
	
	InventoryFolder = Instance.new("Folder", player)
	InventoryFolder.Name = "Iventory"
	
	local PlayerHasData, ItemToLoad = pcall(function()
		
		return InventoryData:GetAsync(PlayerId)
	end)
	
	if PlayerHasData then
		
		if not ItemToLoad then
			
			ItemToLoad = {}
		
		end
		
		for i, v in ipairs(ItemToLoad) do
			
		local SavedItem = Instance.new("StringValue", InventoryFolder)
			SavedItem.Name = v
			SavedItem.Value = "SavedItem"
			
		end
		
	end
	
	
	
	
end)





game:BindToClose(function()
	

	
	local Items = InventoryFolder:GetChildren()
	
	
	for i, v in pairs(Items) do
		
		table.insert(ItemsSaved, v.Name)
		
	end
	
	
	
	InventoryData:SetAsync(PlayerId, ItemsSaved)
		

	print(ItemsSaved)
	
	
end)


game.Players.PlayerRemoving:Connect(function()
	
	local Items = InventoryFolder:GetChildren()


	for i, v in pairs(Items) do

		table.insert(ItemsSaved, v.Name)

	end



	InventoryData:SetAsync(PlayerId, ItemsSaved)


	print(ItemsSaved)
	
	
end)

What do you mean by “do i need to make an bindtoclose and game players removing at the same time?” game:BindToClose and Players.PlayerRemoving fires at different times

In my experience, you only need to use PlayerRemoving.

cause bind to close isn’t like when the game closes? and players player removing when a player in the server leaves so when the server shutdown the code in player removing dont work properly

game:BindToClose fires when the server itself is being shutdown leaving a (at maximum) 30 second window to save player data. PlayerRemoving fires when the server is still up.

Looking at your system, it wouldn’t work because nothing is connected to an individual player, it’ll only save the latest player’s data because it keeps overwriting the InventoryFolder variable. And in addition, the ItemsSaved table will add items that don’t belong to the player (everyone elses data)