Data store not saving

Using this post as a reference, I had tried to go about saving a more structured table, much like what you see in the op in the thread above. However, I don’t understand why I can’t seem to get it to work.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local ServerStorage = game:GetService("ServerStorage")

local player_data = DataStoreService:GetDataStore("player_data")
local tools = ServerStorage.Tools
local InventoryManager = ServerStorage.Inventories
local HttpService = game:GetService("HttpService")

Players.PlayerAdded:Connect(function(player) -- Loading data
	
	local Inventory = Instance.new("Folder") -- Players inventory
	Inventory.Name = player.Name
	Inventory.Parent = InventoryManager
	
	local Cargoes = tools.CargoTypes:Clone()
	Cargoes.Parent = Inventory
	
	local key = "client_wdewdwewewewewewe1234543" .. player.UserId
	local cargoSave = player_data:GetAsync(key)
	print(cargoSave)
	
	if cargoSave then
		cargoSave = HttpService:JSONDecode(cargoSave)
		if cargoSave.Pelts ~= nil then
			if cargoSave.Pelts > 0 then
				print("Found!")	-- This does not print out
				local Pelts = Cargoes.Pelts
				local amount = Pelts.Amount
				amount.Value = cargoSave.Pelts
			end
		end
	end	
end)

Players.PlayerRemoving:Connect(function(player)		-- Saving data
	local key = "client_wdewdwewewewewewe1234543" .. player.UserId
	
	local Inventory = InventoryManager[player.Name]
	local cargoFolder = Inventory.CargoTypes
	
	local inv = {}
	
	for i, v in pairs(cargoFolder:GetChildren()) do
		if v:FindFirstChild("Amount") then
			inv[v.Name] = v.Amount.Value
		end
	end 
	
	local success, err = pcall(function()	
		player_data:SetAsync(key,HttpService:JSONEncode(inv))
		print("end")	-- This does not print out
	end)
	if not success then
		warn(err)
	end			
	Inventory:Destroy()
end)

https://gyazo.com/fdf76d0dc08926a30378e9eac8c88ca7

if you tested this in studio, the PlayerRemoving function never runs because studio closes the game not the player leaving. If you did test it in studio, test it in the actual game instead. Also, further explanation, when games close (like shutting down, etc…) you can use the game:BindToClose function to save everyones data when this happens.

2 Likes