1

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 nameand 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?

  • Hello Ajeet! I get an array with 7 objects in it (one for each category) – Developer-Person Jun 06 '21 at 05:46
  • Yeah sorry I did that and have reposted above, I get the array with objects for each category – Developer-Person Jun 06 '21 at 05:49
  • No problem, here is a sample: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {_id: "60b48c507d68085a5c99eace", name: "Party", description: "Things to party with", __v: 0, createdAt: "2021-05-31T07:12:16.267Z", …} 1: {_id: "60b48c507d68085a5c99ead1", name: "Kitchen", description: "Put liquids in these. Or pens.", __v: 0, createdAt: "2021-05-31T07:12:16.268Z", …} ... – Developer-Person Jun 06 '21 at 05:52
  • 1
    that worked thanks! I didn't realise you could use useEffect twice in the one screen! – Developer-Person Jun 06 '21 at 05:58
  • 1
    @AjeetShah Please add your comment as an answer to allow it to be selected as the correct answer, and to close the question. _Thanks!_ – cssyphus Jun 06 '21 at 22:32
  • @Ajeet I didn't want to hassle you to create the answer so I did it myself and gave you credit hope that's ok. I can delete it if you want to do it yourself? – Developer-Person Jun 07 '21 at 02:50
  • @Developer-Person No. Don't delete it. I like to write as few answers as possible. Keep your answer. – Ajeet Shah Jun 07 '21 at 02:59

1 Answers1

1

From @Ajeet Shah

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

I didn't realise that you could use useEffect twice in the one page, apparently you can!

  • You can use as many `useEffect` as seems best for your app. You should check the official introduction article: https://reactjs.org/docs/hooks-intro.html#complex-components-become-hard-to-understand – Ajeet Shah Jun 07 '21 at 01:22