Why isnt my datastore saving?

So, I want to make a datastore, but it only saves sometimes. I want it to save all the time. Here is the code

local Data = game:GetService("DataStoreService")
local DataStore1 = Data:GetDataStore("DataStore1")


game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Parent = leaderstats
	
	local wins = Instance.new("IntValue")
	wins.Name = "Wins"
	wins.Parent = leaderstats
	
	local playerUserID = "Player_"..player.UserId
	
	local data2
	local success, errormessage = pcall(function()
		data2 = DataStore1:GetAsync(playerUserID)
	end)
	
	if success then
		cash.Value = data2.Cash
		wins.Value = data2.Wins
	end
	
	
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	local playerUserID = "Player_"..player.UserId
	
	local data3 = {
		Cash = player.leaderstats.Cash.Value;
		Wins = player.leaderstats.Wins.Value
	}
	
	local success, errormessage = pcall(function()
		DataStore1:SetAsync(playerUserID, data3)
	end)
	
	
	if success then
		print("Data has saved")
	else
		print("Error for saved message")
		warn(errormessage)
	end
end)

Can anyone tell me whats wrong?

3 Likes

Instead of saving the data when player leaves, save the data when the value changes.

1 Like

How could you do something like this?

1 Like

well if he does that then if everyone changed their value everytime then the datastore request would have a massive request and it would throttle

1 Like

The code will look something like this

cash.Changed:Connect(function(()
ds1:SetAsync(plr.UserId,cash.Value)
end)

Hope it helps

You do have a point

[[30 charrs]]

1 Like

Oh yeah, I just realized. Because if I was to have a big server, it would be too much and the script wouldnt handle the amount of requests.

That would be a problem in simulator games where strength is always being increased.
And UpdateAsync is better and favoured over than SetAsync.

so if I was to replace using updateasync, it would update each time a value was placed?

Please do. It would help.

[30 Chars]

for some complicated things like this i would rather then just use datastore2 or some very useful datastore module

they handle every request the right way so you just can spam new datastores with them but it will be inside tables!

I am not really used to datastore2. I have never even really used it.

here is a topic of mine back in 2019 on why my stats was not showing up

thats outdated and very old just gotta use the documentation for better practice

yikes… its better to find a source more relevant to this time and not ancient

well played, very well played

2 Likes

you could add a debounce or add a thread that has a loop which autosaves the value in intervals

ye but no because i would have to do it on a while loop and loop through all players which is inefficient