Skip to content

Instantly share code, notes, and snippets.

@brlafreniere
Created January 15, 2021 23:22
Show Gist options
  • Save brlafreniere/b4fd4364df16cee88de1f6eea4cc3a22 to your computer and use it in GitHub Desktop.
Save brlafreniere/b4fd4364df16cee88de1f6eea4cc3a22 to your computer and use it in GitHub Desktop.
const TechnicianSelect = (props) => {
const [technicians, setTechnicians] = useState([])
const [selectedIds, setSelectedIds] = useState([])
const [selectedOptions, setSelectedOptions] = useState([])
const [selectedOptionsLoaded, setSelectedOptionsLoaded] = useState(false)
useEffect( () => {
axios({
url: "/users.json?role=technician",
method: "GET"
}).then(response => setTechnicians(response.data))
axios({
url: "/assignments.json?service_order_id=" + props.serviceOrderId,
method: "GET"
}).then(response => {
const ids = response.data.map(assignment => assignment.user_id)
setSelectedIds(ids)
})
}, [])
useEffect( () => {
setSelectedOptions(options.filter(option => {
if (selectedIds.find(id => id == option.value)) return option
}))
setSelectedOptionsLoaded(true)
}, [selectedIds])
// the event parameter contains all of the selected technicians
const changeHandler = (techs_selected, service_order_id) => {
let tech_ids = []
if (techs_selected != null) {
for (let tech of techs_selected) {
tech_ids.push(Number.parseInt(tech.value))
}
}
axios({
url: "/assignments",
method: "POST",
data: {tech_ids, service_order_id}
})
}
const options = technicians.map(technician => {
let option = {
value: technician.id,
label: (technician.first_name + " " + technician.last_name) }
return option;
})
if (selectedOptionsLoaded) {
return (
<Select
options={options}
isMulti
defaultValue={selectedOptions}
onChange={(e) => changeHandler(e, props.serviceOrderId)}
/>
)
} else { return null }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment