I'm fairly new to react
I'm trying it write an update form with react-select and i have a trouble to set the default selection
let flight = useLocation();
if (flight.state) {
flight = flight.state.flightobj
}
is the flight data that needed to be updated ( taken from previous page)
(airlineOptions?.find(({ label }) => label === flight?.airline)
Find the option and format it for select
The problem is that it just wont set the default, i tried to do set {label, value} manually and it works.
Second problem
onSubmit prop in the select not firing for some reason. onSubmit form wise does. I excluded onSubmit from the code .
const CreateFlightForm = () => {
let flight = useLocation();
if (flight.state) {
flight = flight.state.flightobj
}
let [airlineOptions, setAirlineOptions] = useState()
let [airline, setAirline] = useState()
let [opt, setOpt] = useState(airlineOptions ? .find(({
label
}) => label === flight ? .airline));
const handleSubmit = (e) => {
e.preventDefault();
// ... sends to db
}
useEffect(() => {
getAirlines()
}, [])
// let defaultval = () => {
// let test = airlineOptions?.find(({ label }) => label === flight?.airline)
// // console.log(test);
// setOpt(test)
// }
let getAirlines = async() => {
let response = await fetch(`/backend/airlines`)
let data = await response.json()
setAirlineOptions(data.map((airline) => ({
value: airline.id,
label: airline.name
})))
}
return ( <
div className = 'create' >
<
FormHeader headercheck = {
flight
}
/> <
form id = 'app_form'
onSubmit = {
(e) => handleSubmit(e)
} >
<
label > Airline < /label> <
Select required id = 'airline'
isClearable = {
true
}
options = {
airlineOptions
}
defaultValue = {
opt
}
isSearchable = {
true
}
onChange = {
(e) => {
if (e) setAirline(e.value)
}
}
defaultValue = {opt}
/> <
input type = 'submit' > < /input>
<
/form>
<
/div>
)
}
export default CreateFlightForm