Home > Back-end >  Homescreen.js not displaying in localhost/home needed output in browser
Homescreen.js not displaying in localhost/home needed output in browser

Time:09-06

I'm having problems with displaying the rooms of my hotel reservation website. I cant find the solution. Please help me. I've spent 3 hours trying to find solutions

My Homescreen.js

import React ,{useState, useEffect, } from 'react'
import axios from 'axios';


function Homescreen(){

  let [ rooms, setrooms ] = useState([])
  const [loading, setloading] = useState()
  const [error, seterror] = useState()
  useEffect(() => {
    async function getResults() {
      setloading(true)
      const data = (await axios('/api/rooms/getallrooms')).data;
      setrooms(data)
      setloading(false)
      seterror(true)
      setloading(false)
    };
    getResults()
  
  },[])
  

  return (
    <div>
        {loading? (<h1>loading...</h1>) :error ? (<h1>Error</h1>) :(rooms.map(room=>{

            return <h1>{room.name}</h1>

        }))}
       
    </div>
  )
}

export default Homescreen

Output I'm getting Output I'm getting

CodePudding user response:

You are setting error to true in all cases, try to change your code to (using a try catch to detect errors):

function Homescreen() {
    let [rooms, setrooms] = useState([]);
    const [loading, setloading] = useState(false);
    const [error, seterror] = useState(false);
  
    useEffect(() => {
      async function getResults() {
        try {
          seterror(false);
          setloading(true);
          const data = (await axios('/api/rooms/getallrooms')).data;
          setrooms(data);
          setloading(false);
        } catch (e) {
          seterror(true);
          setloading(false);
        }
      }
      getResults();
    }, []);
  
    ...
  • Related