I need to edit products that already contain a type of category but when I receive the data to edit I use useState to set the category data and display it in a select where the user could change the category.
I simply receive from my context the categories and the category that it already has by assigning the product in this way:
const [categoryState, setCategoryState] = useState()
useEffect(() => {
getCategories()
getProduct(params.id)
if(product?._id) {
setFiles(product.img)
setCategoryState(product.category.name) // OK Product Category
}
}, [])
Later in my select I try to show the category to which the product belongs in addition to the other categories in this way:
<select
{...register('category')}
className="border-solid border-2 border-slate-200 w-full p-2"
value={categoryState}
onChange={ e => handleChange(e.target.value)}
>
{ categories.docs.map( data => (
<option
key={data._id}
value={data._id}>
{ data.name }
</option>
))}
</select>
The previous code only shows me the available categories but never shows the category that has the registered product already selected.
If I make the change of the value by the name, in effect, it shows me correctly the name of the category that the product has, being this way:
<select
{...register('category')}
className="border-solid border-2 border-slate-200 w-full p-2"
value={categoryState}
onChange={ e => handleChange(e.target.value)}
>
{ categories.docs.map( data => (
<option
key={data._id}
value={data.name}>
{ data.name }
</option>
))}
</select>
Here using handleChange I can set the new category in useState that the user could choose but a problem arises, when sending to my API I do not need to send the name but the ID of the category.
So my question here is how to show the name of the category that the product already has set, but also when sending to the API, send the ID and not the name of it?