DataStore Isn't Saving A Player's Items

I think this is the problem, correct me if I’m wrong. I added a print for when the player leaves. When I bought a tool and left, the name of the tool didn’t print.

Players.PlayerRemoving:Connect(function(client)
	print("PlayerLeft")
	local key = "client_".. client.UserId
	local tools = {}
	local inventory_folder = inventories[client.Name]
	
	for _, item in pairs(inventory_folder:GetChildren()) do
		table.insert(tools, item.Name)
	end
	
	player_data:UpdateAsync(key, function(prev)
		print(tools) ---THIS IS THE PART
		return tools
		
		end)
		
		inventory_folder:Destroy()
	end)
print("done")

That would be the issue. Unless if it’s not shown, did you define “inventories”, If not that is most likely your issue.

	local inventory_folder = inventories[client.Name]
1 Like

In addition to the other advice you’ve received in this thread, I’d also like to recommend running datastore actions inside a pcall, so that you can handle data errors, for example, passing the player’s data up to the server to retry the save an hour later, if the initial save fails.

Example from your script in Reply #20:

local success, error = pcall(player_data:UpdateAsync(key,function(prev)
if not success then
print(error) -- this print call will only run if success is false
else return tools
end`
1 Like

Should I also use a pcall when I use GetAsync?

Yeah, I defined inventories as

local inventory_folder = Instance.new("Folder")

pcall should be used for threads where you absolutely want to know when there is an error happening, and when you want the opportunity to retry the call without harming other operations in your thread. When errors happen in a script, the function that caused the error gets entirely disconnected. So if you have one single thread related to saving data, and you don’t prevent the error with a pcall, that thread – and any attempt to save data in the future, in that server – effectively goes poof.

You can also abuse pcall to catch errors when loading data, for example, but you really shouldn’t need to because of how GetAsync yields until data is returned.

1 Like