I am working on a reservation form that when I click to edit it, the new page has the form prefilled from the data already in the API. I have the URL set up to go to a route based on the id
with useParams
, but right now I'm only getting a blank form because I can't get the id
number into my GET request It's the first axios get request. The second one is to get the options for my select dropdown list. If you need any more info/code, just let me know.
I have already tried making the axios request a string interpolation, but the console gives me a 400 error and shows the ${id} as undefined.
const { id } = useParams();
useEffect(() => {
axios.all([
axios.get(
`http://localhost:8080/reservations/${id}`,
{
headers: {
'Authorization': 'Bearer ' + sessionStorage.getItem("token")
}
}
),
axios.get(
'http://localhost:8080/room-types',
{
headers: {
'Authorization': 'Bearer ' + sessionStorage.getItem("token")
}
}
)
])
.then(axios.spread((reservationResponse, roomTypesResponse) => {
console.log(reservationResponse.data, roomTypesResponse.data);
setReservation(reservationResponse.data);
setRoomTypes(roomTypesResponse.data);
}))
.catch(() => {
setApiError(true);
})
}, []);
"http://localhost:8080/reservations/:id"
where you likely meant to use a template literal and inject the id
route path parameter valueAxios.all
has been deprecated for years. Use Promise.all
now instead.Use template literal to inject id
value into request URL
`http://localhost:8080/reservations/${id}`
Use Promise.all
to handle array of promise objects
Use an AbortController
and return a useEffect
cleanup function to cancel any in-flight requests when id
changes or the component unmounts
const { id } = useParams();
useEffect(() => {
if (!id) return;
const controller = new AbortController();
const options = {
headers: {
Authorization: 'Bearer ' + sessionStorage.getItem("token"),
},
signal: controller.signal,
};
Promise.all([
axios.get(`http://localhost:8080/reservations/${id}`, options),
axios.get('http://localhost:8080/room-types', options)
])
.then(([reservationResponse, roomTypesResponse]) => {
setReservation(reservationResponse.data);
setRoomTypes(roomTypesResponse.data);
})
.catch(() => {
setApiError(true);
});
return () => {
controller.abort();
};
}, [id]);