Search code examples
javascriptreactjsreact-routerreact-router-dom

Is it possible to call to APIs inside a react-router loader function


I'd like to know if it's possible to make 2 API calls inside a loader function if I am using react-router 6. My ideas was to create an object based on these 2 calls and destruct the object in the rendering component like this:

function MainComponent (){
const {data , reservation} = useRouteLoaderData('room-details');
..
..
}
export default MainComponent;

export async function loader({request, params}) {

    const id = params.roomId;
    const response = await fetch ('http://localhost:8080/rooms/' + id);
    const response2 = await fetch('http://localhost:8080/rooms/reservation/' + id)

    const megaResponse = {
        data: response,  //i tried data:{respose} It ain't work 
        reservation: response2,
    };
    if (!response.ok) {
        throw json({message: 'Something Wrong'}, {status: 500});
    }
    else {        
        return megaResponse; 
    }
}

But i have no success output. I'd really want to make these 2 call in one place, otherwise I will have to use useEffect in a child component. Not a good Idea I think. Thanks


Solution

  • I found the solution, I tried it and it worked. It is as follow:

    function MainComponent (){
    const [data , reservation] = useRouteLoaderData('room-details');
    ..
    ..
    }
    export default MainComponent;
    
    export async function loader({request, params}) {
    
        const id = params.roomId;
    
        return Promise.all([
            fetch ('http://localhost:8080/rooms/' + id),
                fetch('http://localhost:8080/rooms/reservation/' + id)
        ])
        .then(
            ([data, reservation]) =>
            Promise.all([data.json(), reservation.json()]), 
            error => {throw json({message: 'Something Wrong'}, {status: 500});}
        )
        .then(([data, reservation]) => {
            return [data, reservation];
        });
    }
    

    Thanks