React/Redux can’t access properties of object in an array

Working with react and redux toolkit.

I have a form which allows users to create items. The post request must adhere to the relevant mongoose item schema.

Form entries relate to the following stateful values:

  const [name, setName] = useState('');
  const [imageURL, setImageURL] = useState('');
  const [brand, setBrand] = useState('');
  const [category, setCategory] = useState('');
  const [description, setDescription] = useState('');
  const [barcode, setBarcode] = useState('');
  const [countInStock, setCountInStock] = useState('');
  const [message] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [uploadFile, setupLoadFile] = useState('');

I don’t want people making up their own categories so I have a separate categories mongodb table which I populate into the form like this

          <Form.Group controlId='category'>
            <Form.Label>Category</Form.Label>
            <Form.Control
              as='select'
              type='category'
              placeholder='enter Category'
              value={category}
              onChange={(e) => setCategory(e.target.value)}>
              {categories.map((category) => {
                return <option key={category._id}>{category.name}</option>;
              })}
            </Form.Control>
          </Form.Group>

The problem is that on loading the form displays the first category option as default but that option is not set as the category. So if the user fills in the form and does not touch the category drop down options and hits submit, the data will be sent with category as undefined even though to the user it looks like the first category was selected.

I have tried to solve this problem in two ways:

  1. Have the form trigger setCategory on load with the category that is displayed by default (this did not work)
  2. get the first category name and adding it to useState like this:
  const categories = useSelector(getAllCategories);
  let firstCat = categories[0]; //this works
  let firstCatName = firstCat.name; //this fails
  const [category, setCategory] = useState(firstCatName)

This approach fails because for some reason trying to get the name of the first category triggers an error of cannot find property name of undefined, even though the object is there and i can map through the categories array in the form.

Any idea what I am doing wrong here?

This was answered on stackoverflow:

useEffect(() => { 
if (categories.length > 0) {
 setCategory(categories[0].name)
 } }, [categories])

I didn’t realise that you could use useEffect more than once in a react page/component.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.