Home > Mobile >  React-TypeSrcript: Expected 0 arguments, but got 1
React-TypeSrcript: Expected 0 arguments, but got 1

Time:12-24

I'm not sure why I got this error. So basically I'm dispatching the id from Product component to getProduct redux action. Not sure why it isnt working.

// The product component

    const Product: React.FC = () => {
       const { id } = useParams();
    
       const dispatch = useDispatch();
       useEffect(() => {
          dispatch(getProduct(id));
       }, [dispatch, id]);
    
       return (
          <section className="product">
             <div className="bd-container product-container"></div>
          </section>
       );
    };
export default Product;

// getProduct redux action

interface productId {
   id: string | undefined;
}
export const getProduct =
   (id: productId) => async (dispatch: Dispatch<Actions>) => {
      dispatch({
         type: actionTypes.GET_PRODUCT_LOADING,
      });

      try {
         const { data } = await axios.get(`${url}/api/products/${id}`);
         dispatch({
            type: actionTypes.GET_PRODUCT_SUCCESS,
            payload: data,
         });
      } catch (error: any) {
         dispatch({
            type: actionTypes.GET_PRODUCT_FAIL,
            payload: error,
         });
      }
   };

CodePudding user response:

In this line

const dispatch = useDispatch();

you assign the variable dispatch to the function useDispatch which expects 0 arguments.

in this line

dispatch(getProduct(id));

you are calling that function with 1 argument.

CodePudding user response:

Either an action object or action creator function could be passed to dispatch() function you got from useDispatch(). But here you are calling getProduct which is returning nothing, but dispatching actions. Refer to more detail about useDispatch() hook here: https://react-redux.js.org/api/hooks#usedispatch

Redux has a dedicated article on how to deal with async logics here: https://redux.js.org/tutorials/fundamentals/part-6-async-logic

  • Related