I wanted to make a DataStore script that saves values when the player leave, but the problem is when they leave, their leaderstats is gone. Sometimes it works, sometimes it don't.
game.Players.PlayerRemoving:Connect(function(plr)
local key = 'id-' ..plr.userId
local stats = plr.leaderstats
-- OVERWRITE THE CURRENT SAVETABLE --
datastore:UpdateAsync(key, function(savetable)
if savetable then
local newtable = {stats.Money.Value}
return newtable
end
end)
end)

3 comments
build the table outside the UpdateAsync so it does not rely on any value object. Your UpdateAsync function will not save to empty keys ie if savetable is nil.
So I have to use GetAsync() to get the old table and use SetAsync() to overwrite it?
UpdateAsync passes the current value of the key. If the key has not been set before it will be nil. On line 7 you check savetable if the key has never been used you will not save any data as you will have no return value