Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Data Store Not working(API services on), what am I doing wrong?

local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local Cash = Instance.new("IntValue")
	Cash.Name = "Cash"
	Cash.Parent = leaderstats
	
	local playerUserId = "Player_"..player.UserId
	
	
	-- Load data
	local data
	local success, errormessage = pcall(function()
		 data = myDataStore:GetAsync(playerUserId)
	end)
	
	if success then
		Cash.Value = data 
	end	
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "Player_"..player.UserId
	
	local data = player.leaderstats.Cash.Value
	
	local success, errormessage = pcall(function()
		myDataStore:UpdateAsync(playerUserId, data)
	end)
	
	if success then
		print("Data successfully saved!")
	else	
		warn("There was an error!")       ------
		error(errormessage)                   ------ These two are the lines I got the errormessage 
	end 

end)

Hello, I am quite new to DataStores.

I am having trouble with DataStores. I have researched and tried many different methods of Saving Data, However, none work for me. API services were turned on. When I test this in the server and update my Cash Value, it does not save.

In my Output box it says "Unable to cast value to function". Please Help me!

8 comments

0

Just remove "error(errormessage" then

0

"error(errormessage)"*

0

Ok, thanks, I'll try that.

0

wait i don't think I wrote that correctly, its not because of the errormessage

0

I've updated the quetion

0

You have to tell us which line errored.

0

Ok

0

Other than those lines, I am unsure which lines have errored

1 answer

✓ Accepted answer

UpdateAsync takes a function as its second parameter. The function takes the old value of the data stored at the key and should return the new value. Use SetAsync or do:

myDataStore:UpdateAsync(playerUserId, function (old) -- you won't use this parameter, you can omit it
    return data
end)

4 comments

0

Ok, Thanks, I'll try that

0

OMG DUDE THANK YOU SOOOOOOOOOOOOOOOOOOOOOOOO MUCH ! - I HAVE SPENT SO LONG TRYING TO FIX THE SCRIPT! THANK YOU SO MUCH FOR HELPING ME!!!! :DDDDDDD IM SO HAPPY RN

0

Glad I could help

0

:D

This discussion is preserved as it was. New answers, comments, and votes are closed.