Handling objects in component that expects Text

Viewed 67

I'm not sure how to explain my problem, but my API sends the information in objects:

"brand": {
    "id": 48,
    "name": "Nike"
  },

And i need to edit this brand, when i pass this brands on Initial values:

function mapStateToProps(state, props) {
  const quality = state.quality;
  const edition = state.editionBox;
  const levels = state.levels;
  const tenant = state.tenant;
  const productID = props.match.params.id;
  if (productID) {
    // eslint-disable-next-line
    return { initialValues: state.products.productList.find(product => product.id == productID), levels, quality, edition, tenant}
  } else {
    return { brands: state.brands, levels, quality, edition, tenant }
  }
}

My component, expect to just a brandName, not id and name

<Field
 name="brand"
                      label="Marca"
                      component={RenderedSelect}
                      validate={[required]}>
                      {brandsList.map(brand => (
                        <MenuItem key={brand.id} value={brand.name}>
                          {brand.name}
                        </MenuItem>
                      ))}
                    </Field>

This is my redux when i select a brand, i need to get the ID and Name

enter image description here

EDIT: i got this error no console:

enter image description here

EDIT2: My brandList coming from useSelector from redux-state

const brandsList = useSelector(state => state.brands.brandList);
1 Answers

As Erik R., the creator of redux-form answered here, you can stringify the Select's options values, using JSON.stringify:

<Field
  name="brand"
  label="Marca"
  component={RenderedSelect}
  validate={[required]}>
  { brandsList.map(brand => (
    <MenuItem key={brand.id} value={JSON.stringify(brand)}>
      {brand.name}
    </MenuItem>
  ))}
</Field>

Some important notes:

  1. Now, submitting the form, you will have the brand object stringified and you may need converting it back to an object using JSON.parse.
  2. In order to set brand initialValues correctly, please make sure to stringify it firstly. Otherwise, passing an object literal, won't set the initial value of brand Select.
  3. You can abstract and reuse the above two steps, i.e. stringifying/parsing, in your RenderSelect component. In a similar way, Erik R. implemented it in his ObjectSelect.js example.
Related