Knox
Knox
Explore posts from servers
TTCTheo's Typesafe Cult
Created by Knox on 6/24/2024 in #questions
Migrate react-scripts to vite
I have a project using react-scripts 4 with a proxy-dev-server needed to start the app where I have:
const express = require('express')
const app = express()
const { createProxyMiddleware } = require('http-proxy-middleware')
const fs = require('fs')
require('dotenv').config()

const wsProxy = createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000',
ws: true
})

app.use(
'/api/v2',
createProxyMiddleware({
secure: true,
changeOrigin: true,
target: {
protocol: 'https:',
host: '127.0.0.1',
port: 8443,
pfx: fs.readFileSync(process.env.PROXY_CERT_PATH),
passphrase: process.env.PROXY_CERT_PASSPHRASE
}
})
)

app.use('/sockjs-node', wsProxy)

app.use(
'/',
createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000'
})
)

const server = app.listen(3001)

server.on('upgrade', wsProxy.upgrade)
const express = require('express')
const app = express()
const { createProxyMiddleware } = require('http-proxy-middleware')
const fs = require('fs')
require('dotenv').config()

const wsProxy = createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000',
ws: true
})

app.use(
'/api/v2',
createProxyMiddleware({
secure: true,
changeOrigin: true,
target: {
protocol: 'https:',
host: '127.0.0.1',
port: 8443,
pfx: fs.readFileSync(process.env.PROXY_CERT_PATH),
passphrase: process.env.PROXY_CERT_PASSPHRASE
}
})
)

app.use('/sockjs-node', wsProxy)

app.use(
'/',
createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000'
})
)

const server = app.listen(3001)

server.on('upgrade', wsProxy.upgrade)
And I'm migrating the project to use vite. I have almost everything done, can start the app but can't start the session My new vite.config.ts looks like this https://gist.github.com/FACorreiaa/3c87607cb52ee6a52d332b5b2a0875f9 And from the examples I saw I need to start my proxy and vite concurrently:
{
"dev": "concurrently -k \"npm run proxy-dev-server\" \"npm run react:start\"",
"proxy-dev-server": "node proxy-dev-server.js",
"react:start": "vite --port 3000 --host 127.0.0.1",
{
"dev": "concurrently -k \"npm run proxy-dev-server\" \"npm run react:start\"",
"proxy-dev-server": "node proxy-dev-server.js",
"react:start": "vite --port 3000 --host 127.0.0.1",
My server endpoint responds with json https://127.0.0.1:8443/api/v2/system/status status: "operational" But when I try to start my session I get:
useUserSession.ts:10


GET http://localhost:3001/api/v2/session 404 (Not Found)
useUserSession.ts:10


GET http://localhost:3001/api/v2/session 404 (Not Found)
If I go back on the react-scripts configs everything works fine tho. Anyone has any clue on what I might be missing on the vite part ?
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 5/8/2024 in #questions
Migrating react-query v3 to tanstack-query v4
Im almost finishing this migration process
const getChanges = async (): Promise<Changeset | undefined> => {
try {
const { data } = await Axios.get<Changeset | undefined>('/changeset')
return data
} catch {
return undefined
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}

export default useChanges
const getChanges = async (): Promise<Changeset | undefined> => {
try {
const { data } = await Axios.get<Changeset | undefined>('/changeset')
return data
} catch {
return undefined
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}

export default useChanges
Right now the problem im having is on the getChanges function:
Argument of type '() => Promise<Changeset | undefined>' is not assignable to parameter of type 'QueryFunction<Changeset, string[], any>'.
Argument of type '() => Promise<Changeset | undefined>' is not assignable to parameter of type 'QueryFunction<Changeset, string[], any>'.
Deleting the undefined value solves this error highlighting but the fetch of the data fails.
const getChanges = async (): Promise<Changeset> => {
try {
const { data } = await Axios.get<Changeset>('/changeset')
return data
} catch (error) {
throw new Error('Failed to fetch changeset')
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}
const getChanges = async (): Promise<Changeset> => {
try {
const { data } = await Axios.get<Changeset>('/changeset')
return data
} catch (error) {
throw new Error('Failed to fetch changeset')
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}
Missing queryFn for queryKey 'undefined' index.js:1191
XHRGET
http://localhost:3001/api/v2/changeset
[HTTP/1.1 404 Not Found 74ms]

Error: Failed to fetch changeset
Missing queryFn for queryKey 'undefined' index.js:1191
XHRGET
http://localhost:3001/api/v2/changeset
[HTTP/1.1 404 Not Found 74ms]

Error: Failed to fetch changeset
Am I missing something ?
5 replies
TTCTheo's Typesafe Cult
Created by Knox on 4/10/2024 in #questions
React Table v7 Sorting
I have a question regarding react-table v7, its not possible to have server side sorting with the table doing the handle the sorting, right ? From what I see on the examples, if I have client side sort I can have the table take care of it, but If I want it to be server side I need to handle all the logic including function to sort, icons (ascend, descent) etc. Right now I have server side pagination working but the sorting is still being handled by the table and what happens is that the sorting is only applied on the page itself (so for the first 40 elements, being 40 my limit). Im pretty sure I need to do all the logic, I just wanted to avoid having extra work and style everything.
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/5/2024 in #questions
React query useInfiniteQuery (v3) and react table (v7) for server side pagination
Anyone has every connected react-query v3 with react-table v7 ? Im trying to implement a server side paginator with infinite scrolling doing:
const {
data: devicesData,
isFetching,
fetchNextPage,
fetchPreviousPage,
hasNextPage,
isFetchingNextPage,
hasPreviousPage,
isFetchingPreviousPage
} = useDevices({}, pageNumber, pageSize)
const {
data: devicesData,
isFetching,
fetchNextPage,
fetchPreviousPage,
hasNextPage,
isFetchingNextPage,
hasPreviousPage,
isFetchingPreviousPage
} = useDevices({}, pageNumber, pageSize)
And everything seems ok if I implement custom button paginators like:
<button onClick={() => gotoPage(0)} disabled={!hasPreviousPage || isFetchingPreviousPage}>
{'<<'}
</button>{' '}
<button
onClick={() => previousPage()}
disabled={!hasPreviousPage || isFetchingPreviousPage}
>
{'<'}
</button>{' '}
<button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>
{'>'}
</button>{' '}
<button
onClick={() => gotoPage(pageOptions.length - 1)}
disabled={!hasNextPage || isFetchingNextPage}
>
{'>>'}
<button onClick={() => gotoPage(0)} disabled={!hasPreviousPage || isFetchingPreviousPage}>
{'<<'}
</button>{' '}
<button
onClick={() => previousPage()}
disabled={!hasPreviousPage || isFetchingPreviousPage}
>
{'<'}
</button>{' '}
<button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>
{'>'}
</button>{' '}
<button
onClick={() => gotoPage(pageOptions.length - 1)}
disabled={!hasNextPage || isFetchingNextPage}
>
{'>>'}
but have weird behavior on the custom table paginator that react-table renders:
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage
// Get the state from the instance
} = useTable(
{
//@ts-ignore
columns,

nextPage: () => setPageNumber(pageNumber + 1),
previousPage: () => setPageNumber(pageNumber - 1),
//nextPage: fetchNextPage(),
//previousPage: fetchPreviousPage(),
data: devicesByStatus,
state: {
pageNumber,
pageSize
},
manualPagination: true // Set to false to let useTable handle pagination
},
usePagination
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage
// Get the state from the instance
} = useTable(
{
//@ts-ignore
columns,

nextPage: () => setPageNumber(pageNumber + 1),
previousPage: () => setPageNumber(pageNumber - 1),
//nextPage: fetchNextPage(),
//previousPage: fetchPreviousPage(),
data: devicesByStatus,
state: {
pageNumber,
pageSize
},
manualPagination: true // Set to false to let useTable handle pagination
},
usePagination
)
8 replies
TTCTheo's Typesafe Cult
Created by Knox on 2/26/2024 in #questions
Cancel query when query value reaches to 0
Im making a query that returns me a set of values and that value with decrease over time till it reaches 0. I need to fetch every 100ms the query but I want to be able to cancel the query when outdatedObjects reaches 0.
const useDeviceStatus = (options?: UseQueryOptions<any, AxiosError>) => {
const queryData = useQuery(
'device',
async () => {
const { data } = await Axios.get<Device[]>('/system/status/info')
return data
},
{
enabled: true,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
refetchInterval: 100,
...options
}
)
return queryData
}

export default useDeviceStatus
const useDeviceStatus = (options?: UseQueryOptions<any, AxiosError>) => {
const queryData = useQuery(
'device',
async () => {
const { data } = await Axios.get<Device[]>('/system/status/info')
return data
},
{
enabled: true,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
refetchInterval: 100,
...options
}
)
return queryData
}

export default useDeviceStatus
export default function LinearWithValueLabel() {
const [progress, setProgress] = React.useState(1)
const { status, data: deviceStatus, error, isFetching } = useDeviceStatus()
const outdatedObjects = deviceStatus?.info.outdated_objects_count
const total_objects_count = deviceStatus?.info.total_objects_count
const queryClient = useQueryClient()

React.useEffect(() => {
if (!outdatedObjects || outdatedObjects === 0) {
setProgress(0)
return
}
if (outdatedObjects < 1) {
queryClient.setQueryData('device', null)
queryClient.cancelQueries('device')

return
}

const percentage = ((total_objects_count - outdatedObjects) / total_objects_count) * 100

setProgress(percentage)
}, [outdatedObjects])



return (
<>
{outdatedObjects > 0 && (
<Box display="flex" alignItems="center" width={'600px'}>
<LinearProgress
variant="determinate"
value={progress}
sx={{ width: '100%', padding: '2px', borderRadius: '5px', marginRight: '10px' }}
/>

{`${total_objects_count} ` +
'of ' +
`${outdatedObjects}`}

</Box>
)}
</>
)
}
export default function LinearWithValueLabel() {
const [progress, setProgress] = React.useState(1)
const { status, data: deviceStatus, error, isFetching } = useDeviceStatus()
const outdatedObjects = deviceStatus?.info.outdated_objects_count
const total_objects_count = deviceStatus?.info.total_objects_count
const queryClient = useQueryClient()

React.useEffect(() => {
if (!outdatedObjects || outdatedObjects === 0) {
setProgress(0)
return
}
if (outdatedObjects < 1) {
queryClient.setQueryData('device', null)
queryClient.cancelQueries('device')

return
}

const percentage = ((total_objects_count - outdatedObjects) / total_objects_count) * 100

setProgress(percentage)
}, [outdatedObjects])



return (
<>
{outdatedObjects > 0 && (
<Box display="flex" alignItems="center" width={'600px'}>
<LinearProgress
variant="determinate"
value={progress}
sx={{ width: '100%', padding: '2px', borderRadius: '5px', marginRight: '10px' }}
/>

{`${total_objects_count} ` +
'of ' +
`${outdatedObjects}`}

</Box>
)}
</>
)
}
3 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/20/2023 in #questions
Open id view content from Tanstack Table with Tanstack Router
Anyone has any tip how I can render a new view in the current page of a selected item ? So im using tanstack table, query and router and if I want to open a new page when clicking an item and receiving that Item id, everything works wonderfully. But my idea is to have a table and open a view next to it instead of on a new url page.
<RouterLink
to="/page/$id"
params={{ id: props.id }}
<RouterLink
to="/page/$id"
params={{ id: props.id }}
This open a new page inside the id with the router perfectly. But what if I want just to open a new component or view inside the same page ? Anyone has a tip for this ? Any tip appreciated.
41 replies
RRailway
Created by Knox on 6/14/2023 in #✋|help
Release Go app with Docker and godotenv
func LoadEnvVariables() (ServerConfig, error) {
cnf := ServerConfig{}
err := envconfig.Process("", &cnf)
return cnf, err
}
func LoadEnvVariables() (ServerConfig, error) {
cnf := ServerConfig{}
err := envconfig.Process("", &cnf)
return cnf, err
}
I have this function that I use on my server setup to load the .env variable and on my main.go I do a simple load
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
Locally it works but when hosting with a Dockerfile the app crashes because it can't load the env variable
# Start from golang base image
FROM golang:alpine as builder

# Add Maintainer info
LABEL maintainer="a11199"

# Install git.
RUN apk update && apk add --no-cache git

# Set the current working directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and the go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the working Directory inside the container
COPY . .

# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

# Start a new stage from scratch
FROM alpine:latest
RUN apk --no-cache add ca-certificates

WORKDIR /root/

# Copy the Pre-built binary file from the previous stage. Observe we also copied the .env file
COPY --from=builder /app/main .

# Expose port 8080 to the outside world
EXPOSE 8080

#Command to run the executable
CMD ["./main"]
# Start from golang base image
FROM golang:alpine as builder

# Add Maintainer info
LABEL maintainer="a11199"

# Install git.
RUN apk update && apk add --no-cache git

# Set the current working directory inside the container
WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and the go.sum files are not changed
RUN go mod download

# Copy the source from the current directory to the working Directory inside the container
COPY . .

# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

# Start a new stage from scratch
FROM alpine:latest
RUN apk --no-cache add ca-certificates

WORKDIR /root/

# Copy the Pre-built binary file from the previous stage. Observe we also copied the .env file
COPY --from=builder /app/main .

# Expose port 8080 to the outside world
EXPOSE 8080

#Command to run the executable
CMD ["./main"]
The app is deployed but eventually crashes with
2023/06/14 09:44:30 Error loading .env file
open .env: no such file or directory
2023/06/14 09:44:30 Error loading .env file
open .env: no such file or directory
Any clue ? I know this isn't a railway problem more but any feedback would be appreciated.
11 replies
TTCTheo's Typesafe Cult
Created by Knox on 6/5/2023 in #questions
Image component not displaying images
Hey. So using NExtJS with the app directory, I have a card component with
<Image
src={'/images/cover.jpeg'}
alt="back"
className="front"
width={500}
height={500}
priority
onClick={handleClick}
/>
<Image
src={card.src}
alt="card image"
className="front"
width={500}
height={500}
priority
/>
<Image
src={'/images/cover.jpeg'}
alt="back"
className="front"
width={500}
height={500}
priority
onClick={handleClick}
/>
<Image
src={card.src}
alt="card image"
className="front"
width={500}
height={500}
priority
/>
Where the source of the card is this object:
const cardImages = [
{ src: '/images/hiruma.jpg', matched: false },
{ src: '/images/ikki.jpg', matched: false },
{ src: '/images/ippo.jpg', matched: false },
{ src: '/images/kongo.jpg', matched: false },
{ src: '/images/kusanagi.jpg', matched: false },
{ src: '/images/luffy.jpg', matched: false },
{ src: '/images/taiga.jpg', matched: false },
{ src: '/images/takamura.jpg', matched: false },
{ src: '/images/yoko.jpg', matched: false },
];
const cardImages = [
{ src: '/images/hiruma.jpg', matched: false },
{ src: '/images/ikki.jpg', matched: false },
{ src: '/images/ippo.jpg', matched: false },
{ src: '/images/kongo.jpg', matched: false },
{ src: '/images/kusanagi.jpg', matched: false },
{ src: '/images/luffy.jpg', matched: false },
{ src: '/images/taiga.jpg', matched: false },
{ src: '/images/takamura.jpg', matched: false },
{ src: '/images/yoko.jpg', matched: false },
];
Images is inside the public folder. Any tip on why the images aren't being rendered ?
3 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/29/2023 in #questions
Vite config with playwright-ct
on the project im working we are using absolute paths so.. ~/folder/to/path And im currently having this error:
[vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
Error: [vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external
[vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
Error: [vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external
` Ive tried going through the simplest steps and following the documentation but so far nothing works when I run the tests. This is my vite config (sorry, too much code) https://pastebin.com/QtAGwZm1 This is my playwright-config: https://pastebin.com/PQ9TyLZD Any tip please?
1 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/27/2023 in #questions
Jotai migration from v1 to v2
Im trying to create an hook with useHydrateAtoms to reuse in different components:
import type { WritableAtom } from "jotai";
import { useHydrateAtoms } from "jotai/utils";
import type { ReactNode } from "react";

type AnyWritableAtom = WritableAtom<unknown, Array<any>, any>;

type Props = {
initialValues: Iterable<readonly [AnyWritableAtom, unknown]>;
children: ReactNode;
};
export const HydrateAtoms = (props: Props) => {
useHydrateAtoms(props.initialValues);
return props.children
};
import type { WritableAtom } from "jotai";
import { useHydrateAtoms } from "jotai/utils";
import type { ReactNode } from "react";

type AnyWritableAtom = WritableAtom<unknown, Array<any>, any>;

type Props = {
initialValues: Iterable<readonly [AnyWritableAtom, unknown]>;
children: ReactNode;
};
export const HydrateAtoms = (props: Props) => {
useHydrateAtoms(props.initialValues);
return props.children
};
And when using it on the component
type Props = {
things: number;
children: ReactNode;
};

return (
<Provider>
<HydrateAtoms initialValues={[[value1, value2]]}>
{props.children}
</HydrateAtoms>
</Provider>
);
type Props = {
things: number;
children: ReactNode;
};

return (
<Provider>
<HydrateAtoms initialValues={[[value1, value2]]}>
{props.children}
</HydrateAtoms>
</Provider>
);
Im getting this error:
'HydrateAtoms' cannot be used as a JSX component.
Its return type 'ReactNode' is not a valid JSX element.
Type 'undefined' is not assignable to type 'Element | null'.
'HydrateAtoms' cannot be used as a JSX component.
Its return type 'ReactNode' is not a valid JSX element.
Type 'undefined' is not assignable to type 'Element | null'.
Any tip?
1 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/21/2023 in #questions
Vite config with absolute paths
Im trying to make an e2e test for my components and im using absolute paths like
import { component } from "~/shared/component/test";
import { component } from "~/shared/component/test";
On my vite config I have this alias
resolve: {
alias: {
"~": path.resolve(__dirname, "src"),
},
},
resolve: {
alias: {
"~": path.resolve(__dirname, "src"),
},
},
And yet while running the test for a specific component i'm getting an error related to this absolute paths
Error: [vite]: Rollup failed to resolve import "~/types/sidebar" from "src/shared/components/sidebar/Drawer.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
Error: [vite]: Rollup failed to resolve import "~/types/sidebar" from "src/shared/components/sidebar/Drawer.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
Any idea ?
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/31/2022 in #questions
Get session data inside a mutation
Hello. So im trying to create a profile inside a user that is already logged in. So the flow is Create User => Login => Create User Profile Inside the app. My Models:
model User {
id String @id @default(cuid())
email String @unique
username String @unique
password String
emailVerified DateTime?
profile Profile?
accounts Account[]
sessions Session[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now())
deletedAt DateTime @default(now())
role Role @default(USER)
}

model Profile {
id String @id @default(cuid())
bio String?
profession String?
image String?
user User @relation(fields: [userId], references: [id])
userId String @unique
first_name String?
last_name String?
gender Gender
}
model User {
id String @id @default(cuid())
email String @unique
username String @unique
password String
emailVerified DateTime?
profile Profile?
accounts Account[]
sessions Session[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now())
deletedAt DateTime @default(now())
role Role @default(USER)
}

model Profile {
id String @id @default(cuid())
bio String?
profession String?
image String?
user User @relation(fields: [userId], references: [id])
userId String @unique
first_name String?
last_name String?
gender Gender
}
createProfileSchema: publicProcedure
.input(createProfileSchema)
.mutation(async ({ ctx, input }) => {
try {
const session = await getSession({ ctx.session });
const { bio, profession, image, first_name, last_name, gender } = input;
return await ctx.prisma.profile.create({
data: {
bio,
profession,
image,
first_name,
last_name,
gender,
user: { connect: { email: session.data.user.email } },
},
});
} catch (error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: error,
});
}
}),
createProfileSchema: publicProcedure
.input(createProfileSchema)
.mutation(async ({ ctx, input }) => {
try {
const session = await getSession({ ctx.session });
const { bio, profession, image, first_name, last_name, gender } = input;
return await ctx.prisma.profile.create({
data: {
bio,
profession,
image,
first_name,
last_name,
gender,
user: { connect: { email: session.data.user.email } },
},
});
} catch (error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: error,
});
}
}),
Im failing to understand how do I get the session that is logged .. or do I even need it ?
19 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/13/2022 in #questions
Credentials Provider session always return null
So im trying to make the login page work with email and password from the DB and when i click to submit the values im always having the session as null. This is what im doing:
CredentialsProvider({
name: "Credentials",
credentials: {},
async authorize(credentials: any) {
//check user
const user: any = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});

if (!user) {
throw new Error("No user found");
}
console.log("user credentials", user);
const checkPassword = await compare(
credentials.password,
user?.password
);
console.log("user?.password", user?.password);

if (!checkPassword || user.email !== credentials.email) {
throw new Error("Password or Email dont match");
}

return user;
},
}),
],
// Include user.id on session
callbacks: {
session({ session, user }) {
if (session.user) {
session.user.id = user.id;
}
return session;
},
},
session: {
strategy: "jwt",
},
},
jwt: {
secret: "test",
},
secret: "test",
// pages: {
// signIn: "/",
// newUser: "/signin",

// signOut: "/signout",
// error: '/error'
// },
CredentialsProvider({
name: "Credentials",
credentials: {},
async authorize(credentials: any) {
//check user
const user: any = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});

if (!user) {
throw new Error("No user found");
}
console.log("user credentials", user);
const checkPassword = await compare(
credentials.password,
user?.password
);
console.log("user?.password", user?.password);

if (!checkPassword || user.email !== credentials.email) {
throw new Error("Password or Email dont match");
}

return user;
},
}),
],
// Include user.id on session
callbacks: {
session({ session, user }) {
if (session.user) {
session.user.id = user.id;
}
return session;
},
},
session: {
strategy: "jwt",
},
},
jwt: {
secret: "test",
},
secret: "test",
// pages: {
// signIn: "/",
// newUser: "/signin",

// signOut: "/signout",
// error: '/error'
// },
So on my signin page i invoke the signIn method:
async function onSubmitLoginValues(values: LoginValuesProps): Promise<any> {
const result = await signIn("credentials", {
email: values?.email,
password: values?.password,
redirect: false,
callbackUrl: "/",
});
console.log("result", result);
if (result?.ok) router.push("/");
return result;
}
async function onSubmitLoginValues(values: LoginValuesProps): Promise<any> {
const result = await signIn("credentials", {
email: values?.email,
password: values?.password,
redirect: false,
callbackUrl: "/",
});
console.log("result", result);
if (result?.ok) router.push("/");
return result;
}
result returns:
error: null
ok: true
status: 200
url: "http://localhost:3000/"
error: null
ok: true
status: 200
url: "http://localhost:3000/"
5 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/10/2022 in #questions
Good idea to mix prisma and trpc on the [...nextauth].ts file or should call a function from
So I have something like this:
CredentialsProvider({
name: "credentials",
credentials: {
email: {
label: "email",
type: "text",
placeholder: "test@test.io",
},
password: {
label: "password",
type: "password",
},
},
authorize: async (credentials: any) => {
const user = await prisma.user.findFirst({
where: {
email: credentials.email,
password: credentials.password,
},
});

if (user !== null) {
return user;
} else {
throw new Error(
"User does not exists. Please make sure you insert the correct email & password."
);
}
},
}),
],
pages: {
signIn: "/signin",
}
CredentialsProvider({
name: "credentials",
credentials: {
email: {
label: "email",
type: "text",
placeholder: "test@test.io",
},
password: {
label: "password",
type: "password",
},
},
authorize: async (credentials: any) => {
const user = await prisma.user.findFirst({
where: {
email: credentials.email,
password: credentials.password,
},
});

if (user !== null) {
return user;
} else {
throw new Error(
"User does not exists. Please make sure you insert the correct email & password."
);
}
},
}),
],
pages: {
signIn: "/signin",
}
Its my first time using NextAuth and im thinking if doing something like this inside this file is a good idea or if this logic should be inside trpc method ? Can anyone give me any tip / idea please?
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/8/2022 in #questions
i18next bold strings
Anyone has a better (working) solution for this ?
message={i18n.t(
'member-label:form.designConfig.highContrastTooltipMessage',
{ firstScore: `<strong>${3}</strong>`, secondScore, thirdScore },
)}
message={i18n.t(
'member-label:form.designConfig.highContrastTooltipMessage',
{ firstScore: `<strong>${3}</strong>`, secondScore, thirdScore },
)}
I basically want to pass the firstScore as bold but its not working this way or on the string itself
<strong>{{ firstScore }}</strong>
<strong>{{ firstScore }}</strong>
1 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/6/2022 in #questions
Sort imports
So using the create-t3-app im using the https://www.npmjs.com/package/eslint-plugin-simple-import-sort lib to sort my exports because it freaks me out to have these imports unsorted. And i extended my eslint config as follows:
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "simple-import-sort"],
"extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
"rules": {
"@typescript-eslint/consistent-type-imports": "error",
"simple-import-sort/imports": [
"error",
{
"groups": [
// Packages `react` related packages come first.
["^react", "^@?\\w"],
// Internal packages.
["^(@|components)(/.*|$)"],
// Side effect imports.
["^\\u0000"],
// Parent imports. Put `..` last.
["^\\.\\.(?!/?$)", "^\\.\\./?$"],
// Other relative imports. Put same-folder imports and `.` last.
["^\\./(?=.*/)(?!/?$)", "^\\.(?!/?$)", "^\\./?$"],
// Style imports.
["^.+\\.?(css)$"]
]
}
],
"simple-import-sort/exports": "error"
}
}
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "simple-import-sort"],
"extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
"rules": {
"@typescript-eslint/consistent-type-imports": "error",
"simple-import-sort/imports": [
"error",
{
"groups": [
// Packages `react` related packages come first.
["^react", "^@?\\w"],
// Internal packages.
["^(@|components)(/.*|$)"],
// Side effect imports.
["^\\u0000"],
// Parent imports. Put `..` last.
["^\\.\\.(?!/?$)", "^\\.\\./?$"],
// Other relative imports. Put same-folder imports and `.` last.
["^\\./(?=.*/)(?!/?$)", "^\\.(?!/?$)", "^\\./?$"],
// Style imports.
["^.+\\.?(css)$"]
]
}
],
"simple-import-sort/exports": "error"
}
}
Yet the sort isnt working. Anyone ?
1 replies