Ways to retrieve and store basic information or a variable within a session (Solid Beginning)

After experimenting with setting the username and then accessing it in a session on the client side, I encountered an unexpected error. Here's the code snippet that caused the issue:

import { useSession } from "vinxi/http";

function getSession() {
  return useSession({
    password: process.env.SESSION_SECRET
  });
}

export default function Index() {
  const session = getSession();
  session.data.user = "adam"; //assigning the user name
  const username : string = session.data.user //retrieving the user name
  
  return (
    <div>
      <p>Username: {username}</p>
    </div>
  );
}

Answer №1

In order to retrieve a session value, the useSession function must be utilized.

import { useSession } from "vinxi/http";

export async function getUser(): Promise<User | null> {
  const session = await useSession({
    password: process.env.SESSION_SECRET
  });
  const userId = session.data.userId;
  if (!userId) return null;
  return await store.getUser(userId);
}

To set a session value, you should invoke the session.update method. This is an asynchronous function:

await session.update((d: UserSession) => (d.userId = user!.id));

This is how it is implemented with server functions:

export async function login(formData: FormData) {
  const username = String(formData.get("username"));
  const password = String(formData.get("password"));
  // perform validation
  try {
    const session = await getSession();
    const user = await db.user.findUnique({ where: { username } });
    if (!user || password !== user.password) return new Error("Invalid login");
    await session.update((d: UserSession) => (d.userId = user!.id));
  } catch (err) {
    return err as Error;
  }
  throw redirect("/");
}


export async function logout() {
  const session = await getSession();
  await session.update((d: UserSession) => (d.userId = undefined));
  throw redirect("/login");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows: uploadForm.onsubmit = () => { const formData = new FormData(uploa ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

Incorrect tsx date interpretation when dealing with years such as 0022

I am facing an issue with dates in tsx. The problem lies in the fact that when I set a date like 30/11/0022, it interprets the date as 30/11/1922, which is incorrect. Here is the input element I have in tsx: <FormikField name="Birthdate" disa ...

On which platform is the getFeatureInfo request constructed using Cesium?

Currently, I am working with Cesium and Angular. I am trying to locate where the request URL is generated for GetFeatureInfo in Cesium, but unfortunately I am unable to find it. My goal is to display feature information when clicking on the map. However, ...

The error message "Can't resolve all parameters for CustomerService" is preventing Angular from injecting HttpClient

I have a customerService where I am attempting to inject httpClient. The error occurs on the line where I commented //error happens on this line. Everything works fine until I try to inject httpClient into my service. The error message is: `compiler.js: ...

Error message: "Lazy-loaded modules encounter a TypeError stating that '' is not a function when accessed through NGINX."

Hey, I've got some distribution files for you to check out: AOT-enabled dist with Lazy Modules No AOT Lazy Modules dist AOT without Lazy Modules dist Here's what's been going on: When served locally with webpack-dev-server or live-serve ...

Display a React component according to the user's input

Within the first (parent) div, there is an underlined message stating: "This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.ts(2746)". import A from './components/A&ap ...

Observable<Any> Filter

I am currently utilizing Typescript and Angular 4 in my work. Within my project, I have two lists implemented using rxjs/Rx. ... myList: Observable<MyClass[]>; filteredList: Observable<MyClass[]>; ... My objective is to filter the myList base ...

The limit of update depth when using useState with an array generated from a map operation

I'm working on a component where I'm creating a list from an array using map. Each li element in the list has a ref attached to it to capture the getBoundingClientRect().x and getBoundingClientRect().y coordinates, which are then stored in a refs ...

JavaScript: Translating Date into Moment

Is there a way to convert a Date object to Moment in JavaScript? let testDate = new Date(2020, 05, 03, 1, 2); I attempted the following code without success toMoment(testDate) What is the correct syntax to achieve this conversion? ...

Test the HTML element using ngIf async call in Angular 2 with Jasmine unit testing

As I work on writing unit tests for an HTML div with a condition using *ngIf, I come across a specific scenario. <div *ngIf="clientSearchResults$ | async as searchResults" class = 'fgf' #datalist id="mydata" > <app-client-list id=" ...

Assigning values based on conditions for unions of types

I'm currently exploring typescript and facing a challenge with dynamically assigning values to a union type: type Labs = (name === 'dakota') ? 'fruit' | 'veg' : 'plow' | 'field' | 'till'; An ...

The Proper Method to Utilize InputBox with Async/Await in Visual Studio Code

In my VS Code extension development, I am currently exploring the correct usage of an async function with an await statement to fetch data from an input box presented to the user. A part of my code that is causing unexpected behavior is: function runGitC ...

Show information from the state using React and Typescript

I successfully retrieved data from an API using axios and stored it in the state of my React component. However, I am struggling to display this data on the web so that I can list all the information obtained from the API request. I have tried using the ma ...

Unusual Observable behavior in Angular/Typescript leaves developers scratching their heads

I have encountered an issue with a single Angular 2 service: validate() { return this.http.get('api/validate', data); } Consuming the API works fine: this.ValidationService.validate().subscribe(result => { console.log(&a ...

The ngIf statement in the template isn't functioning properly after a refresh; instead, it is causing a redirection to the homepage

I've been developing with Angular 7, trying to display a <div> ... </div> based on multiple values that I declared as : Boolean = false; in the .ts file. These values are updated in ngOnInit, but for some reason, the page keeps redirecting ...

Issue with Angular Testing: Tick function fails to work properly when component initialization includes a timer

Question How can I make the `tick` function work properly so that my test advances by 10s and calls `submit` in my component as expected? Note: I am looking for a solution other than using await new Promise(r => setTimeout(r, 10000)) to avoid having l ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

In TypeScript, how to refer to the type of the current class

Is there a way to reference the current class type in the type signature? This would allow me to implement something like the following: export class Component{ constructor(config?: { [field in keyof self]: any }) { Object.assign(this, config) ...

Securing React: Best Practices for State Management

Consider the following scenario: const UserProfile: React.FC<RouteComponentProps> = (props) => { const { isAdmin} = useContext(GlobalContext); if (isAdmin()) { return <CriticalFeature/>; } else { return <NonCritic ...