DataStore not working

DataStores have been my weakness for a while and it’s one of the simpler aspects of coding that I’ve never looked into. I tried to learn it today and I’ve done everything like the tutorial, alongside adding comments for future reference. However, my DataStore won’t save and doesn’t produce any errors, even with the pcall function, neither the success or errormessage aspect of the pcall function is called.

This is the script: (the comments don’t run as code in the actual roblox script, just the forum)

local DSS = game:GetService("DataStoreService")
local myDS = DSS:GetDataStore("TestDataStore") -- assigning a variable to access (read/write) a 
datastore where it searches for the DS by the name in the argument

-- Loading Data

game.Players.PlayerAdded:Connect(function(player)

    -- Variables

    local leaderstats = Instance.new("Folder", player)
    leaderstats.Name = "leaderstats"

    local Cash = Instance.new("IntValue", leaderstats)
    Cash.Name = "Cash"

    local playerID = player.UserId

    -- Loading Data

    local data

    local success, errormessage = pcall(function() -- if success then run the code in the function, if not 
    return the error message
	    data = myDS:GetAsync(playerID) -- Get sync with DataStore with the player that joined and 
        store the data under the data variable
    end)

    if success then
	    Cash.Value = data -- sets the data variable equivalent to the real-time leaderstats
    end
end)

game.Players.PlayerRemoving:Connect(function(player)

    -- Variables

    local playerID = player.UserId
    local data = player.leaderstats.Cash.Value

    -- Saving Data

    local success, errormessage = pcall(function()
	    myDS:SetAsync(playerID, data) -- saves the value of Cash as data to the "TestDataStore" - one 
       value per DataStore
    end)

    if success then
	    print("Data Saved")
    else
	    print("Unsuccessful Save")
	    warn(errormessage)
    end
end)

I am not pretty sure but it may be because of player datastore not existing yet, I recommend you to write a code like this under .PlayerAdded function:

if not myDS:GetAsync(player.UserId) then
     myDS:SetAsync(player.UserId,0)
end

This code will basically check if player has a existing datastore and if player doesn’t have a existing datastore it will make a datastore entry for it with the value “0” which is basically nothing.

It hasn’t made a difference and nothing has changed. I believe the problem is saving the DataStore, I’m going to print debug the loading to see if that yields an error or anything of concern.

edit: loading the data works fine.

You should test it outside of studio. Sometimes a test in studio will stop before the saving is complete, but it will work fine in a game.

Tried this prior to the solution and it worked, thanks for the help