hono icon indicating copy to clipboard operation
hono copied to clipboard

set method not working when passing a key and value

Open hariyebk opened this issue 10 months ago • 1 comments

What version of Hono are you using?

4.2.1

What runtime/platform is your app running on?

bun

What steps can reproduce the bug?

app.use(async (c, next) => { c.set('message', 'Hono is cool!!') await next() }) app.get("/", (c) => { const message = c.get("message") return c.text(${message}) })

What is the expected behavior?

It must work fine when passing the key "message" and the value "honor is cool!"

What do you see instead?

underneath the key, I encountered an error: "No overload matches this call. Overload 1 of 2, '(key: never, value: never): void', gave the following error".

Additional information

No response

hariyebk avatar Apr 09 '24 08:04 hariyebk

Hi @hariyebk

It's not a bug. Try to pass the generics to new Hono:

type Variables = {
  message: string
}

const app = new Hono<{
  Variables: Variables
}>()

yusukebe avatar Apr 14 '24 01:04 yusukebe

I am having the same issue, Getting Undefined.


import { Hono } from 'hono';

type Variables = string;

export const blogRouter = new Hono<{
  Bindings: {
    DATABASE_URL: string,
    SECRET_URL: string,
  },
  Variables: {
    hello: Variables,
  }
}>();

// Setting the variable in a POST request
blogRouter.post('/set', async (c, next) => {
  console.log('Hi');
  console.log('Setting value...');
  c.set('hello', '12343'); // Setting the value as a string
  console.log('Value set to:', '12343');
  await next();
  return c.text('It has come inside');
});

// Retrieving the variable in a GET request
blogRouter.get('/get', async (c) => {
  const body = c.get('hello');
  console.log('Retrieved value:', body);
  return c.text(`The value is: ${body}`);
});

First sent an string, and it was an success.

Screenshot 2024-07-25 at 8 05 45 AM

When getting the hello back, it is coming as undefined

Screenshot 2024-07-25 at 8 06 56 AM

anything that I am doing wrong in here ?, It would be helpful to know.

SHAIKARSHADA avatar Jul 25 '24 02:07 SHAIKARSHADA

Hi @SHAIKARSHADA Variables are kept within the same request. Variables should be .set and .get in handlers and middleware that are processed in the same request.

EdamAme-x avatar Jul 25 '24 03:07 EdamAme-x

Hey, buddy can't understand 😂 can you help with the code explanation, in your free time.

SHAIKARSHADA avatar Jul 25 '24 05:07 SHAIKARSHADA

Hi @SHAIKARSHADA

@EdamAme-x is right. The value of c.set/c.get changes with each request. And, c.set('hello', '12345') does not execute if GET /get because the routing path is POST /set.

// This middleware for `POST /set`
blogRouter.post('/set', async (c, next) => {
  c.set('hello', '12343') // It's for `POST /set`. It does not effect on `GET /get`
  await next()
  return c.text('It has come inside')
})

yusukebe avatar Jul 27 '24 02:07 yusukebe