Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React not rendering on initial render of filter of an array of objects

On initial render the page doesnt render the filtered array of objects but if i were to save my code, causing another render the filtered array of objects render. Im not quite sure why this is happening.

Ive tried doing the filtering and setting it to a const variable and then performing setFilteredBookings on that const variable. However, the result is the same.

Here is my code for the file excluding imports:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function Booking() {

  const name = localStorage.getItem('name');
  const email = localStorage.getItem('email');
  const [bookings, setBookings] = useState([]);
  const [filteredBookings,setFilteredBookings] = useState([]);
  const dateData = new Date();

  useEffect( () => {
    const fetchBookings = async() => {
      try{
        const customerIDResponse = await axios.get("http://localhost:5000/getUserID/" + name + "/" + email);
        const bookingsresponse = await axios.get("http://localhost:5000/getBookings/" + customerIDResponse.data.SQLdata[0].customerid);
        // filter through the data and make sure no bookings that are before today can be seen
        setBookings(bookingsresponse.data); 
        
        setFilteredBookings(bookings.filter(booking => {
          const bookingtime = new Date(booking.bookingdate).getTime();
          const currenttime = new Date(dateData).getTime()
          return bookingtime >= currenttime 
        }));

      } catch(err){
        // display a message saying error contact developer
        alert("Uncaught error contact owner of website");
      }
    }
    fetchBookings();
  },[])

  

  const handleDelete = async (bookingid) => {
    try{
      await axios.delete("http://localhost:5000/deleteBooking/" + bookingid);
      window.location.reload(); // reload the page so the bookings displayed change
    } catch(err){
      alert("Uncaught error contact owner of website");
      console.log(err)
    }
  }


  return (
    <div className="main">
      <Navbar/>
      <div className="current-bookings-container">
        <div className="bookings-header">Bookings in the next week for {name}</div>
        <div className="current-bookings">
          {/*map current bookings here, each booking has an update and delete function*/}
          {filteredBookings.map( booking => (
            <div className="booking" key={booking.bookingid}>
              <h1>Booking ID: {booking.bookingid}</h1>
              <p>Your booking date: {booking.bookingdate}</p>
              <p>The booking time is: {booking.bookingtime}</p>
              <button className="delete" onClick={()=>handleDelete(booking.bookingid)}>Delete</button>
              <button className="update"><Link to={`/booking/update/${booking.bookingid}`}>Update</Link></button>
            </div>
          ))}
        </div>
      </div>

      <button className="create-booking"><Link to={"/booking/create"}>Create a Booking</Link></button>


    </div>
  )
}

>Solution :

In your fetchBookings function, setBookings and setFilteredBookings are called at the same so therefore the booking still has an initial state value of [].

To fix this issues, store the API response in a const variable and not in the state or do the filter directly on response.data?.filter() instead of booking.filter()

Do this

const bookingsResponse = response.data; 
 setBookings(bookingsResponse); 
  setFilteredBookings(response.data.filter(booking => {
      const bookingtime = new Date(booking.bookingdate).getTime();
      const currenttime = new Date(dateData).getTime()
      return bookingtime >= currenttime 
 }));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading