Is it possible to update a leaderboards and datastores in a systematic way without using a while loop?

Hi.Hope this message find you safe and sound.

game.Players.PlayerAdded:Connect(function(player)
	
	local leaderstats = Instance.new("Folder", player)
	leaderstats.Name = "leaderstats"

	local Cash = Instance.new("NumberValue",leaderstats)
	Cash.Name= "CashValue"
	while wait()do
		Cash.Value = game.Workspace.tycoon.tycoonHouse.Dropper.Value.Value
		
	end

end)

My leaderboards script :point_up_2:

local DataStoreService = game:GetService("DataStoreService")
local myData = DataStoreService:GetDataStore("CashData")


game.Players.PlayerAdded:Connect(function(player)
	
	print("You have entered")

	local UserID = player.UserId
	local data

	print("Pcall starts!")
	local success, errorMessage = pcall(function()

		data = myData:GetAsync(UserID.."-Cash")
	

		print("Hi")
	end)

	if success then
		player.leaderstats.CashValue.Value = data
		print("Hi")
		
	else
		print(":(")
		warn(errorMessage)
	end
	print("Not leaderstats")

	
end)


game.Players.PlayerRemoving:Connect(function(player)
	
	print("Entered")
	
	local UserID = player.UserId
  	
	print("leaved")
	
		local success, errorMessage = pcall(function()
		myData:SetAsync(UserID.."-Cash",player.leaderstats.CashValue.Value)
			print(player.leaderstats.CashValue.Value) -- Value printed as us
		end)
	
	if success then
			
			print("DataSaved")
		else
			print("dataNotSaved")
			warn(errorMessage)
		end
		
end)

My datastore script :point_up_2:

My datastore is currently working very fine.It is able to change the leaderboards’ value to the number that is inserted.I tested out by changing the leaderstats Cash Value and it worked.

However, whenever I join to test, the cash value is reset to 0 ,instead of the data saved.

Is there any viable method?

Thank you sincerely from me.

If it works then this should be in Code Review not Scripting Support, wrong category

I forgot to state the real problem encountering.Can you help by reviewing?Please.Thank you

if you dont want while loop, maybe try this:

game.Workspace.tycoon.tycoonHouse.Dropper.Value.Changed:Connect(function(newValue)
	Cash.Value = newValue
end)

It added as intended yet I have discovered another bug: It reset to 0 when a new part containing a new value touch the collector part which will add the part’s value into the cash value.

If it reset to 0 because the data that loaded has been replaced by tycoon value. maybe sync tycoon value too

	if success then
		player.leaderstats.CashValue.Value = data
		game.Workspace.tycoon.tycoonHouse.Dropper.Value.Value = data

now data that load will not replaced by default tycoon value

But I’m not suggesting that if data stores cant load data. when leave new save data may replace old data
you can skip this spoiler. it rarely happens

so if I have a GUI that display the cash, all I do is just sync the value too?

You can sync with leaderstats or main one you want.