Return function in createAsyncThunk() return second parameter as [object][object] describing errors

Viewed 44

Why is the second parameter of the Async function in the createAscynThunk() middleware returns an object while a string is expected?

Code from where I dispatch

  const handleDateChange = (e) => {
    const date = e.target.value;
    console.log(date, code); // [date, code]
    dispatch(fetchCurrencyByCodeLatestInSpecificDate(date, code));
  };

In the code above date and code variables return correctly when I log them to the console.

In my createAsyncThunk middleware

export const fetchCurrencyByCodeLatestInSpecificDate = createAsyncThunk(
  FETCH_CURRENCIES_BY_CURRENCY_CODE__IN_SPECIIC_DATE,
  async (date, code) => {
    console.log(date, code); /* the date ouput result is correct but code returns an object with data = 
    {extra: undefined, requestId: 'QJrKF6PbWlQQJei9qIpK0', signal: AbortSignal, dispatch: ƒ, getState: ƒ, …}
    dispatch: ƒ dispatch()
    extra: undefined
    fulfillWithValue: ƒ (value, meta)
    getState: ƒ i()
    rejectWithValue: ƒ (value, meta)
    requestId: "QJrKF6PbWlQQJei9qIpK0"
    signal: AbortSignal {aborted: false, reason: undefined, onabort: null}
    } */
    const response = await fetch(`${CURRENCIES_BASE_API_URL}/${date}/currencies/${code}.json`);
    const data = await response.json();
    return data;
  },
);

The return values in the console.

[object][object] describing errors

I tried by exchanging the parameters in the async function and when I did that the date parameter the was returning correctly return the same error.

1 Answers

createAsyncThunk() accept two parameters that is action type and a payloadCreater.

The payloadCreater accepts two arguments. The arg that was passed to the thunk action creator when it was dispatched and the thunkApi that returns an object containing all of the parameters that are normally passed to a Redux thunk function.

The arg: This is useful for passing in values like item IDs that may be needed as part of the request like what I what to do in the code above but If I need to pass in multiple values, I have to pass them together in an object when you dispatch the thunk, like

const handleDateChange = (e) => {
    const date = e.target.value;
    dispatch(fetchCurrencyByCodeLatestInSpecificDate({ date, code }));
  };

them createAsyncThunk() funtion will be

export const fetchCurrencyByCodeLatestInSpecificDate = createAsyncThunk(
  FETCH_CURRENCIES_BY_CURRENCY_CODE__IN_SPECIIC_DATE,
  async (dateCodeObj) => {
    console.log(dateCodeObj);
    const response = await fetch(`${CURRENCIES_BASE_API_URL}/${dateCodeObj.date}/currencies/${dateCodeObj.code}.json`);
    const data = await response.json();
    return data;
  },
);

Read more about createAsyncThuck() payloadCreator which is a callback function at payloadcreator

Related