Cant render the right ID from fetching an API in React

38 Views Asked by At

I'm doing an restaurant app were you can create a booking. You get a booking Id and this bookingId should render on the result page but it comes as undefined. How can I show the booked id? If I insert the bookingId in the browser the right bookingId renders as it should, but not when I press the button that is linked from the bookingpage to the resultpage. What am I doing wrong? How can I render the right Id on the resultpage? I'm using react and the API is made from my teacher.

Bookingform.tsx

import axios from "axios";
import { useEffect, useState } from "react";
import { ChangeEvent, SyntheticEvent } from "react";
import { Link, useParams } from "react-router-dom";

import { IBookings } from "../models/IBookings";

export const BookingForm = () => {
    const { id } = useParams();
    const [restaurants, setRestaurants] = useState<IBookings[]>([]);

    const [addBooking, setAddBooking] = useState({
        restaurantId: '',
        date: '',
        time: '',
        numberOfGuests: 0,
        customer: {
            name: '',
            lastname: '',
            email: '',
            phone: ''
        }
    });

    useEffect(() => {
        getRestaurants();
    }, []);

    const getRestaurants = async () => {
        try {

            const response = await axios.get<IBookings[]>(
                `https://school-restaurant-api.azurewebsites.net/restaurant/65c6276ee125e85f5e15b79f`

            );
            setRestaurants(response.data);
        } catch (error) {
            console.error("Error fetching restaurants:", error);
        }
    };

    const handleInputChange = (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        if (name.startsWith("customer.")) {
            setAddBooking(prevState => ({
                ...prevState,
                customer: {
                    ...prevState.customer,
                    [name.split('.')[1]]: value
                }
            }));
        } else {
            const newValue = name === 'numberOfGuests' ? parseInt(value) : value;
            setAddBooking(prevState => ({
                ...prevState,
                [name]: newValue
            }));
        }
    };

    const onSubmit = (e: SyntheticEvent<HTMLFormElement, SubmitEvent>) => {
        e.preventDefault();
        axios.post("https://school-restaurant-api.azurewebsites.net/booking/create", addBooking)
            .then((response) => {
                console.log('New booking created successfully:', response.data);
            })
            .catch((error) => {
                console.error('Error creating booking:', error);
            });
    };

    return (
        <div className="m-4 border-8 border-pink-600">
            <h2>Make your reservation</h2>
            <form action="" onSubmit={onSubmit}>
                <div>
                    <label>Choose restaurant</label>
                    <select
                        name="restaurantId"
                        value={addBooking.restaurantId}
                        onChange={handleInputChange}>
                    
                        <option value="0">None</option>
                        <option value="65c6276ee125e85f5e15b79f">Happy Dumpling</option>

                    </select>
                </div>


                <div>
                    <label>Date</label>
                    <input
                        type="date"
                        placeholder="Add Date"
                        name="date"
                        value={addBooking.date}
                        onChange={handleInputChange}
                    />
                </div>
                <div>
                    <label>Time</label>
                    <select
                        name="time"
                        value={addBooking.time}
                        onChange={handleInputChange}
                    >
                        <option value="0">0</option>
                        <option value="18.00">18:00</option>
                        <option value="21.00">21:00</option>
                    </select>
                </div>
                <div>
                    <label>How many seats</label>
                    <select
                        name="numberOfGuests"
                        value={addBooking.numberOfGuests}
                        onChange={handleInputChange}
                    >
                        <option value="0">0</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                    </select>
                </div>
                <div>
                    <label>Name</label>
                    <input
                        type="text"
                        placeholder="Name"
                        name="customer.name"
                        value={addBooking.customer.name}
                        onChange={handleInputChange}
                    />
                </div>
                <div>
                    <label>LastName</label>
                    <input
                        type="text"
                        placeholder="LastName"
                        name="customer.lastname"
                        value={addBooking.customer.lastname}
                        onChange={handleInputChange}
                    />
                </div>
                <div>
                    <label>Email</label>
                    <input
                        type="text"
                        placeholder="Email"
                        name="customer.email"
                        value={addBooking.customer.email}
                        onChange={handleInputChange}
                    />
                </div>
                <div>
                    <label>Phone</label>
                    <input
                        type="text"
                        placeholder="Phone"
                        name="customer.phone"
                        value={addBooking.customer.phone}
                        onChange={handleInputChange}
                    />
                </div>
                <button className="btn btn-block" type="submit" value="Save Task">
                    Book a table
                </button>
                <br />
                <Link to={`/booking/${id}`}>Se din bokning här</Link>
            </form>
        </div>
    );
};

BookingRender.tsx

import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";


export const BookingRender = () => {
    const { id } = useParams<string>();
    const [bookingData, setBookingData] = useState(null);

    useEffect(() => {
        if (id) {
            axios
                .get(`https://school-restaurant-api.azurewebsites.net/booking/${id}`)
                .then((response) => {
                    console.log('Get Booking', response.data);
                    setBookingData(response.data);
                })
                .catch((error) => {
                    console.error('Error fetching booking:', error);
                });
        }
    }, [id]);

    

    return (
        <>
            <div>
            {bookingData ? (
                <div>
                    Ditt bokningsId {id}
                    {/* Render booking data here */}
                </div>
            ) : (
                <div>No booking data found</div>
            )}
            </div>
        
        </>
    );};

  

created a booking

see booking

when used insertedId in the browser it works

API

1

There are 1 best solutions below

0
DigpalSinghPanwar784 On

You don't have any value for id so that's why it is undefined in bookingForm.tsx

<Link to={`/booking/${id}`}>Se din bokning här</Link>

Assign the value to id so that it can route to the provided path and will be able to get the value in BookingRender.tsx using useParams Hooks.