aboutsummaryrefslogtreecommitdiff
path: root/modern/src/form/SelectField.js
blob: 78a1688743262ce4cf07b3cfc7434f0fc81b9515 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { FormControl, InputLabel, Select } from '@material-ui/core';
import React, { useState } from 'react';
import { useEffectAsync } from '../reactHelper';

const SelectField = ({ margin, variant, label, defaultValue, onChange, endpoint }) => {
  const [items, setItems] = useState();

  useEffectAsync(async () => {
    const response = await fetch(endpoint);
    if (response.ok) {
      setItems(await response.json());
    }
  }, []);

  if (items) {
    return (
      <FormControl margin={margin} variant={variant}>
        <InputLabel>{label}</InputLabel>
        <Select
          native
          defaultValue={defaultValue}
          onChange={onChange}>
          <option value={0}></option>
          {items.map(item => (
            <option key={item.id} value={item.id}>{item.name}</option>
          ))}
        </Select>
      </FormControl>
    );
  } else {
    return null;
  }
}

export default SelectField;