Greg-A
Greg-A

Reputation: 862

How to call an API in a conditional with React

I would like when I open a modal only launch a service if the modal is open, and re-use the service data for another injection in another component.

Here is the component :

import React from 'react';
import { Modal } from 'react-bootstrap';
import FormResolveDispute from '../forms/form-resolve-dispute';
import { useGetAllMovementsByTiersQuery } from '../../services/EventApi';

const ModalResolveEvent = (props: any) => {
const {show, onClose, dispute} = props;
if (show) {
    const {mouvement} = useGetAllMovementsByTiersQuery(
        {
            qp: new URLSearchParams({
                eventId: dispute.id,
            }).toString(),
        },
        {
            selectFromResult: ({data}) => ({
                movement: data?.items || [],
            }),
        }
    );
    return data;
}
return (
    <>
        <Modal show={show} onHide={onClose} centered={true} scrollable={true}>
            <Modal.Header closeButton>
                <Modal.Title className="text-title">
                    Test
                </Modal.Title>
            </Modal.Header>
            <Modal.Body>
                <FormResolveDispute
                    mvts={mouvement}
                    submitCallback={onClose}
                />
            </Modal.Body>
        </Modal>
    </>
   );
 };

 export default ModalResolveEvent;

here I check if show is true to make the call

 if (show) {
   const {movement} = useGetAllMovementsByTiersQuery(
    {
        qp: new URLSearchParams({
            eventId: dispute.id,
        }).toString(),
    },
    {
        selectFromResult: ({data}) => ({
            movement: data?.items || [],
        }),
    }
);
return movement;

}

and I would like to inject the movement into the FormResolveDispute component.

   <FormResolveDispute mvts={movement} submitCallback={onClose} />

But I have the following error message

TS2304: Cannot find name 'movement'.

I would like to retrieve the movement generated in the conditonnal to send it back to the FormResolveEvent

Could you tell me where the problem is or if there is another way ?

Upvotes: 0

Views: 2032

Answers (1)

edhi.uchiha
edhi.uchiha

Reputation: 364

Please try this.

// create initial state
const [movement, setMovement] = useState([]);

if (show) {
const { movement } = useGetAllMovementsByTiersQuery(
    {
        qp: new URLSearchParams({
            eventId: dispute.id,
        }).toString(),
    },
    {
        selectFromResult: ({data}) => ({
            movement: data?.items || [],
        }),
    }
   );

// set state
setMovement(movement);
}

So in this component, movement props is get from state

<FormResolveDispute
     mvts={movement}
     submitCallback={onClose}
     />

Upvotes: 1

Related Questions