Search code examples
javascriptredux-toolkit

How to use redux toolkit query without React hooks


I have created this mutation in redux toolkit query and now I have to call this mutation endpoint in vanilla Javascript file. How to do this?

import { apiSlice } from "apiHelpers/ApiSlice";

const placeMyOrder = apiSlice.endpoints.placeMyOrder.initiate();

export const PLACE_order = async () => {
  const { data } = await placeMyOrder(orderobj);
  if (data) {
   
  } else {
    
    return;
  }
};

Solution

  • initiate is thunk it needs to be dispatched to work. It's better to use hooks except you have particular reasons like server side rendering for example.

    Here is how to use your query without hooks:

    import { apiSlice } from "apiHelpers/ApiSlice";
     
    export const getServerSideProps = wrapper.getServerSideProps(
      (store) =>
        async ({ orderInfo }) => {
          const { data: order } = await
              store.dispatch(
                  apiSlice.endpoints.placeMyOrder.initiate(orderInfo)
              ); 
    
          return {
            props: {
              order,
            },
          };
        }
    );
    

    Here is how to do it with redux toolkit query and hooks:

    import { apiSlice } from "apiHelpers/ApiSlice";
    
    // It's better to do it where you api is then export usePlaceMyOrder
    const { usePlaceMyOrder } = apiSlice
    
    export const PlaceOrder: FC<Props> = ({ orderInfo }) => {
      const {
        data: order,
        isFetching,
        isLoading,
      } = usePlaceMyOrder(orderInfo, {
        pollingInterval: 0,
        refetchOnMountOrArgChange: true,
        skip: false,
      })
    
      if (isLoading) return <div>Loading...</div>
      if (!order) return <div>Missing order!</div>
    
      return (
        <div>
          {order.name} {isFetching ? '...refetching' : ''}
        </div>
      )
    }
    

    Inside the component, the usePlaceMyOrder hook is called with two arguments: orderInfo (which is passed to the component) and an options object. This hook probably initiates an API request to place an order with the given id and returns the request's status and response data.

    • The options object sets a pollingInterval of 0 milliseconds, meaning the API request will not be repeated every XX milliseconds.
    • refetchOnMountOrArgChange: true means that the hook will re-run the API request whenever the component mounts or the orderInfo argument changes.
    • skip: false means that the API request will not be skipped. You can set it to true when you do not want to do the API call yet

    here is how to dive more into RTKQ