I am trying to render component from a javascript function
export const fetcher = (signal, method, route, content = null) => {
return fetch(`${API_URL}${route}`, options)
.then(res => {
if (res.status === 401 && isLoggedIn())
// SHOW SNACKBAR HERE
return Promise.reject("INVALID_TOKEN");
if (res.status === 500)
// SHOW SNACKBAR HERE
return Promise.reject("UNKNOWN_ERROR");
if ((res.status < 200 || res.status >= 300) && res.status !== 401)
// SHOW SNACKBAR HERE
return Promise.reject("UNKNOWN_ERROR");
if(res.status === 204)
// SHOW SNACKBAR HERE
return res.status;
if (res.headers.get("Content-Type").indexOf("application/json") !== -1)
// SHOW SNACKBAR HERE
return res.json();
return res.status === 200 ? res.text() : res.status;
})
.catch(err => {
console.log(err, `${method?.toUpperCase()} ${route}`);
if (err === "INVALID_TOKEN") {
removeToken();
window.location = "/";
}
else if (err === "UNKNOWN_ERROR") {
window.location = "/500";
}
else if (err.name !== 'AbortError') {
window.location = '/networkerror';
}
return Promise.reject();
});
};
I tried to use HOC but this is not worked for me.
Is it possible to render react elements outside react context ?
Thank you !
Not sure this is possible, at least not in a graceful matter.
What we usually do when fetching, is handle the related events in the component that calls the fetch function.
You can have an error state that you set accordingly to whether the function ends up in the catch block. And then you can conditionally call the needed component from the render.
So for example, something like this:
import { fetchData } from ...
export function Foo() {
const [error, setError] = useState(null);
async const onFetch = () => {
try {
...
await fetch();
} catch (error) {
setError(error);
}
}
useEffect(() => {
// Initial -
onFetch();
}, []);
return (
...
{error !== null && <SnackbarComp error={error} />}
)
}
I know this doens't necessarily answer your question.
Feel free to disregard if not helpful.