All files / src/utils/helpers rejectionMessage.js

100% Statements 10/10
100% Branches 17/17
100% Functions 1/1
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31                                  21x     38x 38x 21x   20x 38x 7x   13x    
/**
 * What to tell a user when a dispatched thunk was rejected.
 *
 * Developer: Allan Ninal
 *
 * Moved here from StudentSearchClass (#267) once the teacher's class roster needed
 * exactly the same thing. Two rules, both learned from what users were actually being
 * shown:
 *
 *   * `action.error.message` is the literal string "Rejected" whenever a thunk uses
 *     rejectWithValue — Redux Toolkit's own marker, not a sentence. It was being
 *     rendered verbatim;
 *   * a TypeError's text ("Cannot read properties of undefined…") reaches the same
 *     field when a thunk's catch block throws while building its rejection.
 *
 * The reason a user can act on, when there is one, is in the payload.
 */
export const DEFAULT_ACTION_ERROR = "Something went wrong. Please try again.";
 
export function messageFromRejection(action) {
    const detail = action?.payload?.detail ?? action?.payload?.message ?? action?.payload?.data?.detail;
    if (typeof detail === "string" && detail.trim()) return detail;
    if (typeof action?.payload === "string" && action.payload.trim()) return action.payload;
 
    const fallback = action?.error?.message;
    if (typeof fallback === "string" && fallback.trim() && fallback !== "Rejected" && !fallback.includes("Cannot read"))
        return fallback;
 
    return DEFAULT_ACTION_ERROR;
}