Skip to content

fix: treat undefined markdown as empty string - #960

Closed
BetterAndBetterII wants to merge 1 commit into
mdx-editor:mainfrom
BetterAndBetterII:fix/undefined-markdown-trim
Closed

BetterAndBetterII wants to merge 1 commit into
mdx-editor:mainfrom
BetterAndBetterII:fix/undefined-markdown-trim

Conversation

@BetterAndBetterII

Copy link
Copy Markdown

Summary

MDXEditor crashed when markdown was undefined/null. Optional chaining only guarded params, so params?.initialMarkdown.trim() threw Cannot read properties of undefined (reading 'trim').

Treat undefined/null as an empty string in postInit (same as init), setMarkdown$, and the pre-ready markdown path so the editor renders empty instead of throwing.

Fixes #803

Test plan

  • npx vitest --run src/test/core.test.tsx (22 passed, including undefined/null markdown and setMarkdown(undefined))

MDXEditor crashed when the markdown prop was undefined because
optional chaining only guarded params, not initialMarkdown itself:
params?.initialMarkdown.trim() threw on reading trim.

Coerce undefined/null to empty string in postInit (matching init),
setMarkdown$, and the pre-ready markdown path.

Fixes mdx-editor#803
@petyosi

petyosi commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Thanks for the PR! One thing to sort out before this moves forward:

This goes against the declared TS types. markdown: string is a required, non-nullable prop, and setMarkdown(markdown: string) is equally strict. So under the contract the library ships, undefined/null are not valid inputs. The PR itself shows this friction:

  • the new tests need undefined as unknown as string casts to pass the type checker
  • the guards need eslint-disable @typescript-eslint/no-unnecessary-condition comments, since TS treats x ?? '' as dead code when x: string

As a result, the runtime would accept values the types say are impossible — TS consumers would silently get an empty editor for a contract violation instead of an error. (The issue reporter also notes the caller-side workaround is trivial: markdown={body ?? ''}.)

To be fair, there is one genuine latent bug fixed here: params?.initialMarkdown.trim() ?? '' — the ?? '' could never fire because .trim() throws first, so (params?.initialMarkdown ?? '').trim() is a real fix.

@BetterAndBetterII could you clarify the necessity for the runtime guards beyond that fix? If we do want to tolerate undefined/null at runtime, I'd prefer widening the public types (markdown?: string, and the same for setMarkdown) so types and runtime agree and the eslint suppressions can be dropped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Resilience on undefined markdown

2 participants