Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hono jsx context is not set if await happens before useContext call #3812

Open
correiarmjoao opened this issue Jan 8, 2025 · 1 comment
Open
Labels

Comments

@correiarmjoao
Copy link

What version of Hono are you using?

4.6.16

What runtime/platform is your app running on? (with version if possible)

Node v22.12.0

What steps can reproduce the bug?

When using useContext in an async component if an await happens before calling useContext function the context is not set to the value used in the provider.

The context in AwaitAfterUseContext will have the messages array, while in AwaitBeforeUseContext it will be null.

import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { useContext, createContext, type FC } from "hono/jsx";

const MessagesContext = createContext<typeof messagesCtxData>(null);

const app = new Hono();

const AwaitAfterUseContext: FC = async () => {
  const messages = useContext(MessagesContext);
  await new Promise((r) => setTimeout(r, 1000));
  return (
    <>
      <h1>Hello Hono!</h1>
      <ul>
        {messages.map((message) => {
          return <li>{message}!!</li>;
        })}
      </ul>
    </>
  );
};

const AwaitBeforeUseContext: FC = async () => {
  await new Promise((r) => setTimeout(r, 1000));
  const messages = useContext(MessagesContext);
  return (
    <>
      <h1>Hello Hono!</h1>
      <ul>
        {messages.map((message) => {
          return <li>{message}!!</li>;
        })}
      </ul>
    </>
  );
};

const messagesCtxData = ["Good Morning", "Good Evening", "Good Night"];

app.get("/after", (c) => {
  return c.html(
    <MessagesContext.Provider value={messagesCtxData}>
      <AwaitAfterUseContext />
    </MessagesContext.Provider>
  );
});

app.get("/before", (c) => {
  return c.html(
    <MessagesContext.Provider value={messagesCtxData}>
      <AwaitBeforeUseContext />
    </MessagesContext.Provider>
  );
});

const port = 3000;
console.log(`Server is running on http://localhost:${port}`);

serve({
  fetch: app.fetch,
  port,
});

What is the expected behavior?

After the await the context would be set to the correct value used in the provider.

What do you see instead?

The context is not set to the value used in the provider, instead it has de initial value.

Additional information

No response

@usualoma
Copy link
Member

usualoma commented Jan 9, 2025

Hi @correiarmjoao, thank you for your report. I will investigate!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants