simpller
simpller

Reputation: 317

React redux doesn't return current state value

I have a problem with redux thunk in react. In the thunk file, I use to dispatch actions and change isSuccess and isLoading flag from the reducer, but in the component, after the API call, I get the previous value of these instead of the current ones.

components.jsx

 await addClient(valueToSubmit, employee.tenantId).then((response) => {
    if (isSuccess) {
      showToast(toastTypes.SUCCESS, translate("client_add_success"));
      resetForm();
      setSubmitting(false);
      toggleModal();
      setFieldsWithError([]);
    } else {
      showToast(
        toastTypes.ERROR,
        message.debugMessage?.includes("exist")
          ? translate("client_exist_error")
          : translate("client_add_error")
      );
      setFieldsWithError(message.payload);
    }
  });

thunk.js

export const addClient = (data, tenant) => async (dispatch) => {
  const tenantId = tenant?.replace(/['"]+/g, "");
  dispatch(requestAddClient());

  return await api(
    "post",
    apiUrl,
    data,
    tenant ? { "tenant-uuid": tenantId } : {},
    false
  )
    .then((response) => {
      return dispatch(receiveAddClient(response.data.payload));
    })
    .catch((err) => {
      return dispatch(errorAddClient(err.response));
    });
};

actions.js

export const requestAddClient = () => {
  return {
    type: REQUEST_ADD_CLIENT,
  };
};

export const receiveAddClient = (client) => {
  return {
    type: RECEIVE_ADD_CLIENT,
    client: client,
  };
};

export const errorAddClient = (message) => {
  return {
    type: ERROR_ADD_CLIENT,
    message,
  };
};

reducer.js

case REQUEST_ADD_CLIENT:
      return {
        ...state,
        client: {},
        isSuccess: false,
        isLoading: true,
      };

    case RECEIVE_ADD_CLIENT:
      return {
        ...state,
        client: action.client,
        clients: [...state.clients, action.client],
        isSuccess: true,
        isLoading: false,
      };

    case ERROR_ADD_CLIENT:
      return {
        ...state,
        client: {},
        message: action.message.data,
        isSuccess: false,
        isLoading: false,
      };

and I can't resolve this problem. If anybody knows the reason, please tell me. Thank you in advance!

Upvotes: 0

Views: 220

Answers (1)

HMR
HMR

Reputation: 39270

In addClient thunk you can rethrow in catch

.catch((err) => {
  dispatch(errorAddClient(err.response));
  return Promise.reject(err.response.data)
});

In your component you can do:

await addClient(valueToSubmit, employee.tenantId).then(
  (response) => {
    showToast(
      toastTypes.SUCCESS,
      translate('client_add_success')
    );
    resetForm();
    setSubmitting(false);
    toggleModal();
    setFieldsWithError([]);
  },
  (message) => {
    //promise was rejected
    showToast(
      toastTypes.ERROR,
      message.debugMessage?.includes('exist')
        ? translate('client_exist_error')
        : translate('client_add_error')
    );
    setFieldsWithError(message.payload);
  }
);

Another (better) way to do it is to use useEffect checking the status of the request from the state using useSelector and triggering what needs to be done based on that value.

Upvotes: 1

Related Questions