DataStore sometimes is loss pls help

Sometimes save data is lost. Is there a way to fix this?

local RunService = game:GetService("RunService")
local DataStore = game:GetService("DataStoreService")
local Cash1 = DataStore:GetDataStore("Cash")

game.Players.PlayerAdded:Connect(function(plr)
local Data = Instance.new("Folder", plr)
Data.Name = "Data"
local Cash = Instance.new("IntValue", Data)
Cash.Name = "Cash"
Cash.Value = 0

---- Datastore ----
coroutine.wrap(function()
local function FetchData(dataType, defaultValue)
local success, data
repeat
success, data = pcall(function()
return dataType:GetAsync(plr.UserId)
end)
if not success then
warn("Failed to load data, retrying...")
wait(1)
end
until success

return data or defaultValue
end
Cash.Value = FetchData(Cash1, Cash.Value)



local loadsave = false

local function saveData()
if not loadsave then
loadsave = true
local function safeSetAsync(dataType, value)
local success
repeat
success = pcall(function()
dataType:SetAsync(plr.UserId, value)
end)
if not success then
warn("Failed to save data, retrying...")
wait(1)
end
until success
end
safeSetAsync(Cash1, Cash.Value)
loadsave = false
end
end

local function connectToChangeSignal(property)
property.Changed:Connect(saveData)
end

connectToChangeSignal(Cash)
end)()
end)

function PlayerLeavingSave(player) 
local DataSaveRemoving = player:FindFirstChild("Data")
if DataSaveRemoving then
local function saveData(key, value)
local success
repeat
success = pcall(function()
key:SetAsync(player.UserId, value)
end)
if not success then
warn("Failed to save data, retrying...")
wait(1)
end
until success
end
saveData(Cash1, DataSaveRemoving.Cash.Value)
print(player.Name.." Removing Save!")
end
end

game.Players.PlayerRemoving:Connect(PlayerLeavingSave)


function ServerShutdown()
if RunService:IsStudio() then return end
print("ServerShutdown!")
for i, player in pairs(game.Players:GetPlayers()) do
task.spawn(function()
PlayerLeavingSave(player)
end)
end
end

game:BindToClose(ServerShutdown)

Try adding a task.wait(5) in the ServerShutdown code, right at the end.

Why did you coroutine.wrap all of the code?

coroutine.wrap
I don’t know, I just started writing a script.
I think it’s necessary.

But i’ll try put task.wait(5) in the ServerShutdown code