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

[@react-aria/live-announcer] "Uncaught Error: document is not defined" when used in render function in SSR #6234

Open
wojtekmaj opened this issue Apr 19, 2024 · 1 comment
Labels
good first issue Good for newcomers

Comments

@wojtekmaj
Copy link
Contributor

Provide a general summary of the issue here

When announce() is used in render function in SSR, it triggers an error: "Uncaught Error: document is not defined".

🤔 Expected Behavior?

announce() to abort if document is not defined

😯 Current Behavior

announce() attempts to create div using document.createElement even in Node.js environment

💁 Possible Solution

if (typeof document === 'undefined') {
  return;
}

🔦 Context

No response

🖥️ Steps to Reproduce

Run the following component in SSR:

function Search() {
  const searchParams = useSearchParams();
  const [searchQuery, setSearchQuery] = useState(searchParams.get('search'));

  const results = use(getResults());

  searchQuery && announce(`Found ${results.length} results`, 'polite');

  return <></>;
}

Version

3.34.1

What browsers are you seeing the problem on?

Other

If other, please specify.

Node.js

What operating system are you using?

macOS Ventura

🧢 Your Company/Team

No response

🕷 Tracking Issue

No response

@reidbarber reidbarber added the good first issue Good for newcomers label Apr 19, 2024
@snowystinger
Copy link
Member

Thanks for the issue!

I don't think you should use an announce in the render function, it has a side effect. I think you should put it inside an effect which wouldn't run on the server anyways. That, or put it in an interaction callback.

In addition, you may have this announced more times than you expect because you're relying on renders, which are not guaranteed and in React 18+ may actually run multiple times in their concurrent model. In an effect you can guard against extraneous calls.

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

No branches or pull requests

3 participants