2

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
craigmiller160
  • 5,751
  • 9
  • 41
  • 75
  • Does it help if you replace `axios.get('/expense-tracker/api/oauth/user').then((res) => res.data)` with `axios.get('/expense-tracker/api/oauth/user').then((res) => res.data).catch((err) => { throw err })`? I think otherwise `createResource` can't capture the exception. – edemaine Jun 28 '22 at 17:30

0 Answers0