rsm-hcd / AndcultureCode.JavaScript.React

Common patterns, functions, etc... used when building react applications
6 stars 8 forks source link

usePageErrors hook adds non-string objects to array #67

Open brandongregoryscott opened 3 years ago

brandongregoryscott commented 3 years ago

The usePageErrors hook correctly checks the result as an instance of a ResultRecord to pull out error messages and returns early. However, result can come from anywhere - in cases where it is an Error thrown, the array that we are returning as pageErrors is no longer a string array - it might be a [Error, string] or objects of any other shape. This can cause issues when mapping out what consumers expect to be an array of plain strings to JSX.

Example of React error in development when an Error is thrown and caught by handlePageLoadError, then mapped in an unordered list ![image](https://user-images.githubusercontent.com/11774799/113778801-d71e2700-96fa-11eb-9112-dae99de569d3.png)

Add a safe guard to check for a string or otherwise try to coalesce the object into a string:

if (typeof result === "string") {
    setPageErrors((errors: string[]) => [...errors, result]);
    return;
}

setPageErrors((errors: string[]) => [...errors, result.toString()]);