0

I have React that loads data from DB and displays them:

const Car= () => {

    let history = useNavigate();
    let {id} = useParams();

    const [car, setCar] = useState<CarInterface>();

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

    const getData = () => {

        console.log("LOADING")
        fetch('http://localhost:8080/car/' + id)
            .then((res) => res.json())
            .then((res) => {
                setCar(res);
                console.log(res);
            }).catch(e => {
            console.log("ERROR");
            setCar(undefined)
        })
    }

    return (
        <div className="car">
            {car!= null ? (
                <div className="car-wrapper">
                    <div className="car-title-wrapper">
                        <h1 className="car-title">{car.title}</h1>
                    </div>
                    <div className="car-des">{car.description}</div>
                    <div className="car-info">
                        <ul>{
                            car.parts.split(";").map((part) => (
                                <li>{part}</li>
                            ))
                        }</ul>
                        <img className="car-img"/>

                    </div>
                </div>
            ) : null}
        </div>
    )
}

export default Car;

This component is loaded when certain route is hit:

<div className="app">
    <CarHeader/>
        <Routes>
            <Route path="/" element={<Home/>}>
            </Route>
            <Route path="/car/new" element={<CreateCar/>}>
            </Route>
            <Route path="/car/:id" element={<Car/>}>
            </Route>
        </Routes>
</div>

However, console.log("LOADING") is called twice, that means that component is loaded twice and thus hitting DB two times. Why is this happening? Why is the component loading twice? The state of component is not being changed.

THanks for help

Johnyb
  • 980
  • 1
  • 12
  • 27
  • Sorry i can't comment, here's a [question](https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar) that has some good answers. – Zkh Sep 03 '22 at 15:25

0 Answers0