How to keep an option of a select element selected based on the id value fetched from the DB in ReactJS?

Viewed 17

I am using muse ant design template. I have created a component CaptainEditForm like this:-

function CaptainEditForm({
  // States
  loggedInUser,
  carCategoryList,
  carCategoryListLoading,
  carCategoryListError,
  locationList,
  locationListLoading,
  locationListError,
  userById,
  userByIdLoading,
  userByIdError,

  // Actions
  getAllCarCategories,
  getAllLocations,
  getUserById,
}) {
...............
...............
}

const mapState = state => ({
  loggedInUser            : selectorLoggedInUser(state),       // loggedInUser State

  carCategoryList         : selectorCarCategoryList(state),          // car category list State
  carCategoryListLoading  : selectorCarCategoryListLoading(state),   // car category list loading State
  carCategoryListError    : selectorCarCategoryListError(state),     // car category list error State

  locationList            : selectorLocationList(state),          // location list State
  locationListLoading     : selectorLocationListLoading(state),   // location list loading State
  locationListError       : selectorLocationListError(state),     // location list error State

  userById                : selectorUserById(state),          // country list State
  userByIdLoading         : selectorUserByIdLoading(state),   // country list loading State
  userByIdError           : selectorUserByIdError(state),     // country list error State
})

const mapDispatch = dispatch => ({
  getAllCarCategories     : ()=> dispatch(getAllCarCategoriesStart()),  // car category data action
  getAllLocations         : ()=> dispatch(getAllLocationsStart()), // location data action
  getUserById             : (id)=> dispatch(getUserByIdStart(id)) // country data action
})

export default connect(mapState, mapDispatch)(CaptainEditForm);

In the component function, I am rendering the form like this

return (
        <Form {...layout} form={form} name={formTitle(window.location.pathname)} onFinish={onFinish}>
            <Form.Item name="name" label="Name" value={userById.name} rules={[{ required: true }]}>
              <Input value={userById.name}/>
            </Form.Item>
            <Form.Item name="phone_number" label="Phone Number" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            {
              carCategoryListLoading
              ? <Loader message={"Loading Car Category List"} description={"Listing all car category data"} type={"success"}/>
              : <Form.Item name="car_category" label="Can Handle" rules={[{ required: true }]}>
                  <Select mode="multiple" placeholder="Select a option and change input text above" allowClear>
                    <Option key={0} value="0">None</Option>
                    {carCategoryList && carCategoryList.length > 0 && carCategoryList.map((category, indexCat) => {
                      return (
                        <Option key={parseInt(parseInt(indexCat) + 1)} value={category.id}>{category.name}</Option>
                        )
                    })}
                  </Select>
                </Form.Item>
            }
            {
              locationListLoading
              ? <Loader message={"Loading Location List"} description={"Listing all location data"} type={"success"}/>
              : <Form.Item name="location" label="Location" rules={[{ required: true }]}>
                  <Select placeholder="Select a option and change input text above" allowClear value={userById.locationId}>
                    <Option key={0} value="0">None</Option>
                    {locationList && locationList.length > 0 && locationList.map((locationData, indexLoc) => {
                      return (
                        <Option key={parseInt(parseInt(indexLoc) + 1)} value={locationData.id}>{locationData.name}</Option>
                        )
                    })}
                  </Select>
                </Form.Item>
            }  
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">{formCardTitle(window.location.pathname)}</Button> &nbsp;
              <Button htmlType="button" onClick={onReset}>
                Reset
              </Button>
            </Form.Item>
          </Form>
  );

As you can see, I am having two select element, one of them is multiple.

While loading the page, I am populating the user data into the form elements via this way:-

    if(typeof userById !== undefined && userById !== null)
    {
      form.setFieldsValue({
        name: userById.name,
        phone_number: userById.phoneNumber,
      });
    }

However, I don't know how to populate data (keep an option selected) in an select element. I tried to set the value of the Select element like this:-

location: userById.locationId

But it behaved in a weird way. The Select element started to look like a textbox with the value, ie. the id of the location being displayed.

How can I fix this?

0 Answers
Related