mskocik / svelecte

Flexible autocomplete/select component written in Svelte,
https://svelecte.vercel.app
MIT License
471 stars 43 forks source link

async support for createTransform #209

Closed shubhendumadhukar closed 9 months ago

shubhendumadhukar commented 1 year ago

I am trying to use Svelecte with creatable=true.

In my use case:

const createTransform = async (/** @type {string} */ inputValue, /** @type {string} */ creatablePrefix, /** @type {string} */ valueField, /** @type {string} */ labelField) => {
  console.log({ inputValue, creatablePrefix, valueField, labelField });
  const record = await createTag(inputValue);
  return {
    id: record.id,
    [valueField]: record.name,
    [labelField]: creatablePrefix + record.name,
  };
};

This however does not work, understandably, because createTransform probably doesn't support promises. I can make it work by modifying the function as follows:

const createTransform = (/** @type {string} */ inputValue, /** @type {string} */ creatablePrefix, /** @type {string} */ valueField, /** @type {string} */ labelField) => {
  console.log({ inputValue, creatablePrefix, valueField, labelField });
  createTag(inputValue);
  return {
    [valueField]: inputValue,
    [labelField]: creatablePrefix + inputValue,
  };
};

I would however like my createTransform function to return the id value of record created in DB. Is there a way to make createTransform support promises/async functions?

mskocik commented 1 year ago

Yes, this is current limitation, which can't be fixed without some internal refactoring. Marked for v4.

mskocik commented 9 months ago

Added in v4, which has just been released

shubhendumadhukar commented 9 months ago

Thanks! Tested and it works as expected.

Not sure if I should be asking this here or create a new issue but I had a query regarding the change in the fetch parameter. As per the changelog, it now expects a string. Would it expect the response in specific format? I mean I changed the fetch param to the API endpoint and my dropdown shows a list of undefineds, I guess I was just wondering how is it parsing the values for the dropdown without my custom fetch override there to parse it for Svelecte.

Edit: Nevermind. Figured it out. Using this in the params list makes it work: valueField="name" labelField="name" valueAsObject

mskocik commented 9 months ago

Svelecte tries to get those fields automatically. It probably failed to determinate the labelField because it seems your response return object with only one property. Am I right?

shubhendumadhukar commented 9 months ago

That's right. Explicitly specifying the field fixed the issue.