Search code examples
react-nativenanoid

Nanoid can't be used in react-native


I don't know exactly what happened when I'm using the nanoid package in react native it's shown some kind of below error. I'm not sure about it.

I hope someone help from this community.

Thanks in advance.

Scenario: I just import to the nanoid package.

import { nanoid } from 'nanoid';
Error: React Native does not have a built-in secure random generator. If you don’t need unpredictable IDs use `nanoid/non-secure`. For secure IDs, import `react-native-get-random-values` before Nano ID.    
at node_modules\react-native\Libraries\LogBox\LogBox.js:148:8 in registerError
at node_modules\react-native\Libraries\LogBox\LogBox.js:59:8 in errorImpl
at node_modules\react-native\Libraries\LogBox\LogBox.js:33:4 in console.error
at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:104:6 in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:171:19 in handleException
at node_modules\react-native\Libraries\Core\setUpErrorHandling.js:24:6 in handleError
at node_modules\react-native\Libraries\polyfills\error-guard.js:49:36 in ErrorUtils.reportFatalError   
at node_modules\metro\src\lib\polyfills\require.js:204:6 in guardedLoadModule
at http://192.168.43.19:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false&minify=false:203661:3 in global code

Solution

  • Issue resolved

    I have resolved this issue by using the following functions.

    So I think in the nanoid used crypto module so in react-native it doesn't exist.

    For that, we need to use a nanoid/non-secure module. Below I have also used customAlphabet method.

    Finally it works. :)

    import { customAlphabet } from 'nanoid/non-secure'; 
    
    const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 10);