0

I'm having some trouble with react-bootstrap (or more likely this is a problem with JavaScript). I'm using a select with dynamically loaded content. Selecting some element updates the id hook. But if I don't select anything (for example if here is only one element in the list) id hook doesn't get updated. What is the best solution to update hook with actual value of select even if it hasn't been touched by user?

I'm thinking of manually launching onChange event after the form is loaded or adding a default empty disabled option to my select.

Any suggestions?

Here is my code:

const [categories, setCategories] = useState([]);
const [id, setId] = useState(0);

useEffect(() => {
    fetchData();
}, []);

async function fetchData() {
    try {
        const data=await getAll();
        setCategories(data)
        } catch (e) {
            console.error(e);
        }
    }

export interface Category{
    id:number,
    name:string
}

<Form.Control as="select" onChange={(e) => setId(parseInt(e.target.value))}>
    {categories.map((category: Category) => {
        return <option value={category.id}>{category.name}</option>;
    })}
</Form.Control>
Andrei Yusupau
  • 587
  • 1
  • 11
  • 30
  • 1
    How about you `setId()` to the first element of the array after you fetch the data in `fetchData`? – kunquan Dec 01 '20 at 12:49
  • @kunquan, Tried your solution: updated `const [categories, setCategories] = useState([]);` to `const [categories, setCategories] = useState([]);` Added `.then(() => setId(categories[0].id));` after `fetchData` , now I get `Unhandled Rejection (TypeError): categories[0] is undefined`. – Andrei Yusupau Dec 01 '20 at 13:29

1 Answers1

1

now I get Unhandled Rejection (TypeError): categories[0] is undefined

It's expected as in the function fetchData now the categories value is [] and not the value you just set (why this is the case read this question. In short the function will use the component state value at the time the function state and it will keep this value until the function exit)
So you can fix your code by doing this instead

async function fetchData() {
    try {
        const data=await getAll();
        setCategories(data)
        setId(data[0].id)
        } catch (e) {
            console.error(e);
        }
}
kunquan
  • 1,127
  • 1
  • 10
  • 24