Shop data store cash?

I’m using a kit to set up a shop system, how would I add datastore to this?

local items = game.ReplicatedStorage:WaitForChild("Items")


game.Players.PlayerAdded:Connect(function(plr)
	
	
	local ls = Instance.new("Folder")
	ls.Name = "leaderstats"
	ls.Parent = plr
	
	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Value = 1000
	cash.Parent = ls
end)


game.ReplicatedStorage:WaitForChild("OnItemBought").OnServerEvent:Connect(function(plr, itemBought)
	
	if itemBought and itemBought:IsA("Tool") and itemBought.Parent == items then
		
		
		local cash = plr.leaderstats.Cash
		
		if cash.Value >= itemBought.ShopGuiInfo.Price.Value then
			
			cash.Value -= itemBought.ShopGuiInfo.Price.Value
			
			itemBought:Clone().Parent = plr.Backpack
		end
	end
end)```

Just use datastore service, use get async to get the value saved or 1000 and a playerremoving function and save it inside of there.

local items = game.ReplicatedStorage:WaitForChild("Items")
local cashds = game:GetService("DataStoreService"):GetDataStore("Cash")

game.Players.PlayerAdded:Connect(function(plr)
	
	
	local ls = Instance.new("Folder")
	ls.Name = "leaderstats"
	ls.Parent = plr
	
	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Value = cashds:GetAsync(plr.UserId) or 1000 --get the data or if there is no data 1000 start cash.
	cash.Parent = ls
end)


game.ReplicatedStorage:WaitForChild("OnItemBought").OnServerEvent:Connect(function(plr, itemBought)
	
	if itemBought and itemBought:IsA("Tool") and itemBought.Parent == items then
		
		
		local cash = plr.leaderstats.Cash
		
		if cash.Value >= itemBought.ShopGuiInfo.Price.Value then
			
			cash.Value -= itemBought.ShopGuiInfo.Price.Value
			
			itemBought:Clone().Parent = plr.Backpack
		end
	end
end)

--save it

game.Players.PlayerRemoving:Connect(function(plr)
	cashds:SetAsync(plr.UserId, plr.leaderstats.Cash.Value)
end)
1 Like

I have a few data saving modules that you should take the time to learn!

Andrew bereza’s super cool data module (super easy and efficent):

DS2, by kampfkarren (more advanced and also efficent) :

I have literally never had data issues with either of these modules