Firstly, I’d like to say that I am just starting with programming and not sure if the provided details are sufficient.
I’m encountering an error when trying to access data within the updateUser method in Supabase.
Supabase docs – Update user
const updateUserMetadata = async (formData) => {
const idSegmentOne = Math.floor(Math.random() * 1e10).toString()
const idSegmentTwo = Date.now().toString()
const id = idSegmentOne + idSegmentTwo
const snippet = {id: id, name: formData, body: input.input}
try {
const { data, error } = await supabaseClient.auth.updateUser({
data: { mdSnippets: [ ...data.user.user_metadata.mdSnippets, snippet ] }
})
// console.log(data)
error
? toast.error('Saving snippet failed.')
: toast.success('Snippet saved successfully.')
console.log('Updating metadata error (try):', error)
} catch (error) {
toast.error('Saving snippet failed')
console.log('Updating metadata error (catch):', error.message)
}
}
I believe that the problem is related to spreading the existing values in the array:
[ …data.user.user_metadata.mdSnippets, snippet ]
When attempting to access the data object to spread those values, I’m getting Cannot access ‘data’ before initialization error. The error comes from the catch block console log.
The function is called from another component in the following way:
const onSubmit = (formData) => {
updateUserMetadata(formData.snippetName)
// getUserMetadata()
}
I think that I am trying to access the relevant key-value pair in the correct way as I have checked the shape of the object with the commented out console log you can see after the try block.
I’ve tried declaring data as empty object before the try block, like below, but I am not even sure if that applies to the scope of the try block.
let data = {}
Tried setTimeout to see if maybe after some time the data object would be initialized:
try {
const { data, error } = await supabaseClient.auth.updateUser({
data: {
mdSnippets: await new Promise((resolve) => {
setTimeout(() => {
resolve([...data.user.user_metadata.mdSnippets, snippet])
}, 1000)
})
}
})
But… everything works as expected if I modify the array to contain only the snippet without spreading existing data.
try {
const { data, error } = await supabaseClient.auth.updateUser({
data: { mdSnippets: [ snippet ] }
})
Thanks
Jakub Kozuszek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.