Reputation: 6273
I'm new to SolidJS and I'm having a weird error with resources. Here is my code:
export const authUserResource = createResource(
() => axios.get<AuthUser>('/expense-tracker/api/oauth/user').then((res) => res.data)
);
export const MyComponent = () => {
const [data] = authUserResource;
createEffect(() => console.log('HasChecked', data.loading, data.error, data()));
return (
// ...
)
}
The intent of the API call is to retrieve data on the currently authenticated user, or to return a 401 if the user is not currently authenticated. My intent is to then redirect the user based on their authentication status.
Well, the API is called and it is returning a 401 because the user is not authenticated. All of this is expected. What is not behaving is the SolidJS resource.
If the API returns a 401, I would expect the SolidJS resource data to meet these conditions:
data.loading === false
data.error instanceof Error
data() === undefined
Instead, I am finding that it is still at these conditions, based on the console.log statement in the above code example:
data.loading === true
data.error === undefined
data() === undefined
I also get an "Uncaught Error in Promise" error message in the browser JS console.
I'm hoping to figure out what I am doing wrong here to make the resource correctly handle the error so that I can gracefully handle this in my application.
Upvotes: 3
Views: 1756
Reputation: 443
I also get an "Uncaught Error in Promise" error message in the browser JS console.
I also had the same issue and this comment: https://github.com/solidjs/solid/discussions/705#discussioncomment-2968407 helped.
You access data()
but it is not allowed when there is an error. So you have to guard the call to data()
with data.state === "ready"
or via the other means as described here: https://docs.solidjs.com/references/api-reference/basic-reactivity/createResource#version-140-and-later
My intent is to then redirect the user based on their authentication status.
I would do this inside authUserResource()
, handle the 401 there and only use the resource/signal result for injecting the API data into the view.
Upvotes: 1