Home > front end >  Expected 0 arguments, but got 1 in redux with typescript
Expected 0 arguments, but got 1 in redux with typescript

Time:11-15

So I have an async thunk function in redux:

export const fetchItem = createAsyncThunk('item/fetchItem', async (id: number) => {
    const res = await fetch(`${apiUrl}/${id}`)
    .then(res => res.json())

    return res        
})

And here is my fetch function in react, it fetches the item by the html id of the event target (an tag):

const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => {
        useAppDispatch(fetchItem(e.target.id))   
    }

The error is in the fetchItem and it says: Expected 0 arguments, but got 1. I even tried just using:

useAppDispatch(fetchItem(1))  

And got the same error.

useAppDispatch looks like this:

import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch} from "./redux/store";

export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector()

export const useAppDispatch = () => useDispatch<AppDispatch>() 

CodePudding user response:

  1. useAppDispatch is a hook and can be used only directly inside component's body
  2. useAppDispatch takes 0 arguments, but you pass 1
  3. useAppDispatch returns a dispatch function that you wanted to use
// inside your component
const dispatch = useAppDispatch()
const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => {
  dispatch(fetchItem(e.target.id))   
}
  • Related