Data not being saved?

When I load in, and change my data and leave, it prints saying that it’s saving the new data amount. But when I re-join it reverts back to the default amount?

local DefaultData = {
	Cash = 500,
	PurchasedItems = {}
}

local StoredData = {} -- Stored data for all players

--// Load player data on join
function DataManager.Load(player)
	-- Create leaderstats and data
	local Leaderstats = Instance.new("Folder")
	Leaderstats.Name = "leaderstats"

	local Cash = Instance.new("IntValue")
	Cash.Name = "Cash"

	Leaderstats.Parent = player
	Cash.Parent = Leaderstats
	
	-- Get saved data
	local Data
	local Success, Error = pcall(function()
		print(DataStore:GetAsync(player.UserId).Cash) -- Prints '500'
		Data = DataStore:GetAsync(player.UserId) or DefaultData
	end)
	
	if Success then -- Data loaded
		Cash.Value = Data.Cash -- Set cash value
	else -- Data did not load
		warn(Error)
		player:Kick("Your data failed to load: " .. Error)
	end
	
	StoredData[player] = Data -- Save the players data to a global table
	
	--// Update StoredData when cash changes
	Cash:GetPropertyChangedSignal("Value"):Connect(function()
		StoredData[player].Cash = Cash.Value
	end)
end

--// Save player data on leave
function DataManager.Save(player)
	local Success, Error = pcall(function()
		print("Saving", StoredData[player].Cash) -- Prints 'Saving 100000'
		DataStore:SetAsync(player.UserId, StoredData[player])
	end)
	
	if not Success then -- Data did not save
		warn(Error)
	end
	
	StoredData[player] = nil -- Clear data from global table
end
1 Like

Are you testing from Studio? Maybe the server closes before the data can be saved?

1 Like

If he had api turned on it should save as if it’s a normal game

1 Like

Try to test your game via the roblox client or maybe you didn’t activate API access in Settings

Reply for XxCrazysZz12: oh okay

It would print out an error if he didn’t have it activated.

1 Like

I cannot see the problem, but I am able to give you some changes.

  1. You can change the Cash:GetPropertyChangedSignal("Value") to Cash.Changed as it is the same and Changed also gives out the new value.
  2. (Optional if you want to name your variables property to be easily identified)
    In the pcall for GetAsync, you can just return like:
local Success, Response = pcall(function()
	print(DataStore:GetAsync(player.UserId).Cash) -- Prints '500'
	return DataStore:GetAsync(player.UserId) or DefaultData
end)

The response will either give out an error or what GetAsync returns.

1 Like