Home > database >  Why is my component returning before executing useEffect hook?
Why is my component returning before executing useEffect hook?

Time:08-16

My code is going to be quite explanatory in itself.

export default function ViewCustomer() {
    const [customer, setCustomer] = useState();
    const {id} = useParams();

    useEffect(() => {
        CustomerService.getCustomerById(id).then(res => {
            setCustomer(res.data);
        });
    }, [id]);

    return (
        <div>
           {customer.first_name}
        </div>
    );
}

My code gives customer is undefined error. This is happening because useEffect hook is not executing before return is being executed. How and why is this happening and how can I fix this?

CodePudding user response:

This is by design and you shouldn't try to fix it. Assume that customer will be undefined for the first render, and handle that case. It will have the correct value for the second render.

You can for example render a 'loading spinner', or nothing at all but React is asking you to make an explicit decision on what to do while your data is still being loaded.

  • Related