диспетчеризация не является функцией Next.js +thunk загружает данные пользователя после входа в систему

Когда я пытаюсь getUserProfile(), я получаю сообщение об ошибке typeError, что диспетчеризация не является функцией.

Необработанная ошибка времени выполнения Ошибка: действия должны быть простыми объектами. Используйте специальное ПО промежуточного слоя для асинхронных действий.

export const fetchUserProfile = (userData) => ({
 type: types.GET_USER_PROFILE,
 userData,
});

// преобразователь

export const loginUser = (credentials) => async (dispatch) => {
 dispatch(loginRequest(credentials));

 try {
  const userToken = await userService.login(credentials);
  await dispatch(loginSuccess(userToken));

  getUserProfile();
  } catch (error) {
   const message = await errorMessage(
  error,
  "There was a problem processing your request"
  );
    dispatch(loginFailure(message));
  }
};

export const getUserProfile = async (dispatch) => {
  try {
   const profileData = await userService.getProfileData();

   dispatch(fetchUserProfile(profileData));
 } catch (e) {
    console.log(e);
  return [];
} 
 };

person Mariia Konchak    schedule 02.11.2020    source источник


Ответы (2)


Вам нужно отправить все преобразователи, заменить

getUserProfile();

с

dispatch(getUserProfile())
person thedude    schedule 02.11.2020
comment
После этого я получил: Ошибка: Действия должны быть простыми объектами. Используйте специальное ПО промежуточного слоя для асинхронных действий. - person Mariia Konchak; 03.11.2020

Ваша getUserProfile должна быть функцией, которая принимает свои собственные аргументы, когда вы ее отправляете, а затем она может быть либо функцией обратного вызова, которая принимает dispatch в качестве аргумента (это исходит из промежуточного программного обеспечения Redux Thunk), а затем эта функция имеет функции, которые возвращают action объекты , ИЛИ это может быть просто функция, которая напрямую возвращает объект action (я знаю, это сбивает с толку, но вы действительно сделали это правильно для своего действия loginUser):

export const getUserProfile = () => async (dispatch) => {
  try {
    const profileData = await userService.getProfileData();

    dispatch(fetchUserProfile(profileData));
   } catch (e) {
    console.log(e);
    return []; // this shouldn’t be returning an empty array, if anything it should be dispatching an action for errors that can be displayed to the user 
   } 
};

Этот слишком простой пример дает представление о том, что происходит (нажмите Run code snippet):

// the "dispatch" function that would come from 
// the Redux Thunk middleware
const dispatch = (action) => action((args) => console.log("dispatch:", JSON.stringify(args, null, 2)));

// a "setUserProfile" action that returns an object
const setUserProfile = (payload) => ({
  type: "SET_PROFILE",
  payload
});

// a "fetchUserProfile" action that returns an object
const fetchUserProfile = () => ({ type: "FETCH_USER" });

// a "showError" action that returns an object
const showError = error => ({ type: "FETCH_USER/ERROR", payload: error });

// while the "getUserProfile" action doesn't have any arguments of 
// its own, it accepts a "dispatch" callback function as the SECOND 
// set of arguments, then other actions are dispatched (which return
// their own objects)
const getUserProfile = () => async(dispatch) => {
  try {
    // dispatches the "fetchUserProfile" action 
    // which just returns: { type: "FETCH_USER" }
    dispatch(fetchUserProfile());
    
    // fetching data from API
    const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const data = await res.json();

    // dispatches the "setUserProfile" with data from API 
    // which returns: { type: "SET_PROFILE", payload: data }
    dispatch(setUserProfile(data));
  } catch (e) {
    console.log(e);
    dispatch(showError(e.message));
  }
};

// dispatching the "getUserProfile" function above
// optionally, you can add arguments here, but then these would be
// a part of the FIRST set of arguments to the function
dispatch(getUserProfile());
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>

person Matt Carlotta    schedule 03.11.2020