Datastore2: Value gets updated but only when I rejoin the game

I’m trying to save a table using datastore2
Which it “saves” kind off, I guess.
I’m following a quest system Udemy course, but he uses normal datastore.

local ServerScriptService = game:GetService("ServerScriptService")
local DataStore2 = require(script:FindFirstChild("DataStore2", true))



local function getData()
	local userData = {
		["Gold"] = 1000,
		["Vermin"] = 0,
		["OnQuest"] = false,
		["QuestsDone"] = 1,
		["QuestComplete"] = false,
		["QuestItem"] = "none",
		["RewardPaid"] = false,
		["WaterDB"] = true,
		["HasWater"] = false
	}
	return userData
end
DataStore2.Combine("DEVKEY3","questdata")
game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)

		local userDataStore = DataStore2("questdata", player):Get(getData())

		DataStore2("questdata", player):Set(userDataStore)
		warn(userDataStore)
local plrGold = Instance.new("IntValue", leaderstats)
plrGold.Name = "Gold"
plrGold.Value = userDataStore["Gold"]
DataStore2.SaveAll(player)

This is basically the datastore script, I use.

I use SaveAll, because I don’t know how else to save it.
I used to make a different datastore for each value and use :OnUpdate()
Maybe this is what causing it?

--gain gold
dataTable["Gold"] = dataTable["Gold"] + questMod.Quests[thisQuest].reward
-- aka dataTable["Gold"] = dataTable["Gold"] + 10
warn(dataTable)
userDataStore:Set(dataTable)

The problem is when I gain gold using that line, It gets saved, but will only load when I rejoin the game.

dsImage1

dsImage2
after increasing gold

dsImage3
after rejoining the game

Any idea how to fix this?
I feel like I’m all over the place, but I hope you can make sense of what I’m saying.

Thanks for your time
XYZLambda

edit:

--gain gold
dataTable["Gold"] = dataTable["Gold"] + questMod.Quests[thisQuest].reward
pGold.Value = dataTable["Gold"]
userDataStore:Set(dataTable)

this works for updating in game. While it works…Is this how your supposed to do it?

Yes, your edit is correct.

However rather than setting plrGold.Value everywhere you update the players gold, you could bind the OnUpdate listener to your userDataStore store.

local userDataStore = DataStore2("questdata", player)

userDataStore:OnUpdate(function(newUserData)
	plrGold.Value = newUserData["Gold"]
end)

So I think I understand what you’re saying.
I changed the code a little bit.

local userDataStore = DataStore2("questdata", player)
local userDataTable = userDataStore:Get(getData())
userDataStore:OnUpdate(function(newData)
        plrGold.Value = newData["Gold"]
end)
--gain gold
dataTable["Gold"] = dataTable["Gold"] + questMod.Quests[thisQuest].reward
userDataStore:Set(dataTable)

This is correct?

Yep that’s correct! Now it’s more future proofed with less duplicate code.

1 Like

Thank you, I think I understand it now. Lets see if everything saves how I want it to