S
SolidJS•4mo ago
Anish Neupane

solidjs createResource doesn't show error when there was an error i.e 401 Invalid credentials

createResource data.error always false
8 Replies
Anish Neupane
Anish Neupane•4mo ago
import { createForm, SubmitHandler, zodForm } from '@modular-forms/solid'
import { A } from '@solidjs/router'
import { createEffect, createResource, createSignal, Show } from 'solid-js'
import { z } from 'zod'

import MyTitle from '../components/MyTitle'
import { useAuth } from '../context/Auth'
import { BACKEND_URL } from '../utils'

const loginSchema = z.object({
email: z.string().email('Enter a valid email'),
password: z.string().min(8, 'Enter a valid password')
})

export type LoginFormType = z.infer<typeof loginSchema>

const loginUser = async (values: LoginFormType) => {
const response = await fetch(`${BACKEND_URL}/login-admin/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(values, null, 4)
})
return response.json()
}

const Login = () => {
const { login } = useAuth()

const [loginValues, setLoginValues] = createSignal<LoginFormType | null>(null)

const [data] = createResource(loginValues, loginUser)

const [loginForm, { Form, Field }] = createForm<LoginFormType>({
validate: zodForm(loginSchema),
validateOn: 'touched',
initialValues: {
email: '',
password: ''
}
})

const handleSubmit: SubmitHandler<LoginFormType> = async values => {
setLoginValues(values)
}

createEffect(() => {
console.log(data(), 'data')
console.log(data.error ? '1' : '2')
})
return (
<>
<MyTitle title='Login' />
<div>
<Form onSubmit={handleSubmit}>
..................
</Form>
<div>
<A href='/forget-password'>Forget password?</A>
</div>
</div>
</>
)
}

export default Login
import { createForm, SubmitHandler, zodForm } from '@modular-forms/solid'
import { A } from '@solidjs/router'
import { createEffect, createResource, createSignal, Show } from 'solid-js'
import { z } from 'zod'

import MyTitle from '../components/MyTitle'
import { useAuth } from '../context/Auth'
import { BACKEND_URL } from '../utils'

const loginSchema = z.object({
email: z.string().email('Enter a valid email'),
password: z.string().min(8, 'Enter a valid password')
})

export type LoginFormType = z.infer<typeof loginSchema>

const loginUser = async (values: LoginFormType) => {
const response = await fetch(`${BACKEND_URL}/login-admin/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(values, null, 4)
})
return response.json()
}

const Login = () => {
const { login } = useAuth()

const [loginValues, setLoginValues] = createSignal<LoginFormType | null>(null)

const [data] = createResource(loginValues, loginUser)

const [loginForm, { Form, Field }] = createForm<LoginFormType>({
validate: zodForm(loginSchema),
validateOn: 'touched',
initialValues: {
email: '',
password: ''
}
})

const handleSubmit: SubmitHandler<LoginFormType> = async values => {
setLoginValues(values)
}

createEffect(() => {
console.log(data(), 'data')
console.log(data.error ? '1' : '2')
})
return (
<>
<MyTitle title='Login' />
<div>
<Form onSubmit={handleSubmit}>
..................
</Form>
<div>
<A href='/forget-password'>Forget password?</A>
</div>
</div>
</>
)
}

export default Login
Brendonovich
Brendonovich•4mo ago
error is only present when the fetcher function throws. fetch won't throw as long as there's a valid response, even if it's a 401
Anish Neupane
Anish Neupane•4mo ago
but
import { createSignal, createResource } from "solid-js";
import { render } from "solid-js/web";

const fetchUser = async (id) =>
(await fetch(`https://swapi.dev/api/peopl/${id}/`)).json();

const App = () => {
const [userId, setUserId] = createSignal();
const [user] = createResource(userId, fetchUser);

return (
<>
<input
type="number"
min="1"
placeholder="Enter Numeric Id"
onInput={(e) => setUserId(e.currentTarget.value)}
/>
<span>{user.loading && "Loading..."}</span>
<span>{user.error && "Error"}</span>
<div>
<pre>{JSON.stringify(user(), null, 2)}</pre>
</div>
</>
);
};

render(App, document.getElementById("app"));
import { createSignal, createResource } from "solid-js";
import { render } from "solid-js/web";

const fetchUser = async (id) =>
(await fetch(`https://swapi.dev/api/peopl/${id}/`)).json();

const App = () => {
const [userId, setUserId] = createSignal();
const [user] = createResource(userId, fetchUser);

return (
<>
<input
type="number"
min="1"
placeholder="Enter Numeric Id"
onInput={(e) => setUserId(e.currentTarget.value)}
/>
<span>{user.loading && "Loading..."}</span>
<span>{user.error && "Error"}</span>
<div>
<pre>{JSON.stringify(user(), null, 2)}</pre>
</div>
</>
);
};

render(App, document.getElementById("app"));
https://www.solidjs.com/tutorial/async_resources?solved show error it use fetch
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
Brendonovich
Brendonovich•4mo ago
i assume the peopl/ is intentional? json() is throwing a syntax error since the html response isn't valid json, it's not the fetch that's throwing
No description
Anish Neupane
Anish Neupane•4mo ago
Thank you for your explanation 😊, I will use axios instead of fetch.
Brendonovich
Brendonovich•4mo ago
ah yeah axios throws on non-200 aye
<Alterion.Dev>
<Alterion.Dev>•4mo ago
axios is massively overkill, consider using itty-fetcher instead
GitHub
GitHub - kwhitley/itty-fetcher: An even simpler wrapper around nati...
An even simpler wrapper around native Fetch to strip boilerplate from your fetching code! - kwhitley/itty-fetcher
<Alterion.Dev>
<Alterion.Dev>•4mo ago
Size of axios v1.6.7 is 30.5 kB (minified), and 11.7 kB when compressed using GZIP. Size of itty-fetcher 0.9.4 is 1.3kB (minified), and 784B when compressed using GZIP.
Want results from more Discord servers?
Add your server
More Posts