A basic Hook Code question

Hi there,

Dastaset name: “jobs”
‘category’ is a Reference field Key.

When the category field is updated, I would like to copy the Label of the category input (rather than its ID) to a different Text field - ‘newcategory’.

What should my code look like?
Thanks a lot!

In data.js:

export function jobs_beforUpdate(item, context) {
if(!item.category){return item;}
return wixData.get("jobs", item._id)
.then(r => {
if (r.category === item.category) {return item;}
  return wixData.get("categoriesCollection", item.category);
} )
.then(r => {
item.categoryLabel = r.categoryLabel;
return item;
})
}

P.S the " return wixData . get ( “jobs” , item . _id )" is just to see if the category has changed. You can skip it if you want.

Hi @jonatandor35 ,
Thank you for your prompt reply.

I do need the code to see if the category has changed.
Not sure what “categoriesCollection” is. I need to copy the category labels as a string (text) to a different column (newcategory) in the same dataset (jobs).
Please take a look at the code on my system.

The red dots say ‘wixData’ is not defined .

@omri Sorry for interrupting, you can add the following code on the first line of your code itself →

import wixData from 'wix-data';

+replace " categoriesCollection" by the collection name (the collection that the category value refers to).

Hi @jonatandor35 & @ajithkrr , Thank you,

The following code works!
Only the newcategory column in jobs dataset, gets the _id column values from the categories dataset while I want it to receive the title column values (from categories dataset).

import wixData from 'wix-data';

export function jobs_beforeUpdate(item, context) {
if(!item.category){return item;}
return wixData.get("jobs", item._id)
.then(r => {
if (r.category === item.title) {return item;}
 return wixData.get("categories", item.title);
} )
.then(r => {
item.newcategory = r.category;
return item;
})
}

jobs - the main dataset containing a category column that is a Reference field & a newcategory which is a text field. categories - a second dataset containing the category Reference field options in the title column.