Skip to content
Myr

Snippet to demonstrate async RNG in ReactNative; Fixes #88 (#93)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Documentation update that fixes ai/nanoid#88. * Fix, this time without heavy-handed and involuntary reformatting by Prettier.

authored by joelgetaction · committed by Andrey Sitnik · parent bce6f49 · Browse files · 1 file+29 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+29 added−5 removed

  • other:+29 added−5 removed

1 file+29 added−5 removed

modified:README.md+29 added-5 removed
122 unmodified lines
123in our [ID collision probability] calculator.124125[ID collision probability]: https://zelark.github.io/nano-id-cc/126127### React Native128128### React Native and Web Workers129To generate secure random IDs in React Native, you must use a native130random generator like [react-native-securerandom](https://www.npmjs.com/package/react-native-securerandom). Since `react-native-securerandom`131generates its random bytes on the native side, your React Native JS code must communicate with it asynchronously over the JS bridge. For example, as follows:132130React Native and Web Worker don’t have access to secure random generator.133```js134import { generateSecureRandom } from 'react-native-securerandom';135import format from 'nanoid/async/format';136import url from 'nanoid/url';137138// Using Promises139format(generateSecureRandom, url, 21).then(id => {140 // id is a random ID141 console.log('random ID is', id); //=> xnCahQadzHuI1QjcbYHBE142});143144// Using async/await145async function useRandomID() {146 // id is a random ID147 const id = await format(generateSecureRandom, url, 21);148 console.log('random ID is', id); //=> A6WZ9Kz6961u0Wc8h22O1149}150```151152### Web Workers153154Web Workers don’t have access to a secure random generator.155132Security is important in ID, when ID should be unpredictable. For instance,156Security is important in IDs, when IDs should be unpredictable. For instance,157in “access by URL” link generation.158135If you don’t need unpredictable IDs, but you need React Native136or Web Workers support, you can use non‑secure ID generator.159If you don’t need unpredictable IDs, but you need Web Workers support, 160you can use non‑secure ID generator.161162```js163const nanoid = require('nanoid/non-secure')164model.id = nanoid() //=> "Uakgb_J5m9g~0JDMbcJqLJ"
131 unmodified lines