javascriptreactjsaxiosreact-router-dom

get url endpoint for react axios get request to fill form for editing


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);
    })
}, []);

Solution

  • Issues

    1. You are using the string literal "http://localhost:8080/reservations/:id" where you likely meant to use a template literal and inject the id route path parameter value
    2. Axios.all has been deprecated for years. Use Promise.all now instead.

    Solution Suggestion

    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]);