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?

7
  • Hello Ajeet! I get an array with 7 objects in it (one for each category) Commented Jun 6, 2021 at 5:46
  • Yeah sorry I did that and have reposted above, I get the array with objects for each category Commented Jun 6, 2021 at 5: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", …} ... Commented Jun 6, 2021 at 5:52
  • 1
    that worked thanks! I didn't realise you could use useEffect twice in the one screen! Commented Jun 6, 2021 at 5: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! Commented Jun 6, 2021 at 22:32

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

You can use as many useEffect as seems best for your app. You should check the official introduction article: reactjs.org/docs/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.