I Re-made it and used UpdateAsync() instead of SetAsync().
I tested it and it works.
local DataStoreService = game:GetService("DataStoreService")
local DataStoreName = DataStoreService:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
local stats = Instance.new("Folder")
stats.Name = "leaderstats"
stats.Parent = player
local coins = Instance.new("IntValue")
coins.Name = "XP"
coins.Parent = stats
local data
local success, errormessage = pcall(function()
data = DataStoreName:GetAsync(player.UserId.."-XP")
coins.Value = data
end)
if success then
print("Data Loaded")
else
print("Error")
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall (function()
DataStoreName:UpdateAsync(player.UserId.."-XP",function(old)
local newvalue1 = old
newvalue1 = player.leaderstats.XP.Value
return newvalue1
end)
end)
if success then
print("Data has been saved")
else
print("Error")
warn(errormessage)
end
end)