reactjsredux-formacts-as-taggable-onreact-select

react-select to just include values in form, rather than value: '' and label: ''


I'm including react-select in my rails project, within a redux-form, it all works well, except that the backend I'm submitting the form to doesn't like the {value, label},

I'd like my form field to just include a list of the values.

here's my form code:

export const renderTagsSelect = props => {
  const { input, initialValues } = props;
  return (
    <Creatable
      {...props}
      value={input.value || initialValues}
      resetValue={initialValues}
      onChange={value => input.onChange(value)}
      onBlur={() => input.onBlur(input.value)}
    />
  );
};

render() {
  <form onSubmit={handleSubmit(doSaveItem)}>
    <Title>Modifica Item</Title>
    <Field
      name="title"
      label="Titolo"
      component={renderInput}
      validate={required()}
    />
    <br />
    <span>Tags</span>
    <br />
    <TagsFormSelector name="tag_list" tags={item.tag_list} />
    <SubmitButton type="submit" disabled={pristine || submitting}>
      Salva modifiche
    </SubmitButton>
  </form>
}

when submitting, the JSON generated by the form is like:

 "tag_list": [
    {
      "label": "cena",
      "value": "cena"
    },
    {
      "label": "Paesaggi cittadini",
      "value": "Paesaggi cittadini"
    }
  ],

my backend is implemented in rails with acts_as_taggable_on, prefers to receive just something like this:

"tag_list: ["cena", "Paesaggi cittadini"]

for non-optimised this could be, I prefer having the backend drive the API.

Any clues how to achieve this?


Solution

  • Following kuiro5 suggestion I fixed it in the form with a normaliseData function:

    in the form:

         <form onSubmit={handleSubmit(doSaveItem)}>
            [..]
            <TagsFormSelector name="js_tag_list" tags={item.tag_list} />
            [..]
    

    in the doSaveItem:

    const doSaveItem = (data, dispatch, props) => {
      normaliseData(data);
    
      return dispatch(saveItem(props.item.id, data)).catch(response => {
        throw new SubmissionError(f.errorsFromProps(response));
      });
    };
    

    the normaliseData:

    const normaliseData = data => {
      data["js_tag_list"] &&
        (data["tag_list"] = data["js_tag_list"].map(tag => tag.value));
    

    and other data normalisations.

    this made it work.