Home > OS >  Next.js trouble with document.getElementById
Next.js trouble with document.getElementById

Time:06-20

Error: set failed: value argument contains an invalid key (__reactFiber$3ojngwn446u) in property 'users.id.username.userN'. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"

That is the error code I got for line 25. From what Ive been able to gather its because userN cant be a null value. Is their any work around for document.getElementById? because it returns a null value until the submit.

    function writeUserData(userId, userN, address) {
        const db = getDatabase();
        const reference = ref(db, 'users/'   userId);

        set(reference, {
            username: userN,
            walletAddress: address
        });
    }


    return (
        <>
            <div>
                <p className = "account-Info" >address: {address}</p>
            </div>
            <div id="form">
                <h2 className='user-Create' > Create Username</h2>
                <form id='set-User'>
                    <input id='userName' className='user-Create' type='text' placeholder="username" required minlength='3' maxlength='20' pattern="[a-zA-z0-9_] " title='only letterns, numbers, and underscores'/>
                    <button className='user-Create' type="submit" onClick={ getValue() }>Link Username</button>
                </form>
            </div>
        </>
    );

    function getValue() {
        userN = document.getElementById('userName');
        writeUserData('id', { userN }, { address })
    }
}

}

export default Username;`

CodePudding user response:

You need to create a variable in the component/page state. Then bind it to the input and use it for your function.

const [username, setUsername] = useState('')
...
<input id='username' type='text' value={username} onChange={event => setUsername(event.target.value)}/>
...
writeUserData('id', { username }, { address })

Since NextJS is server side, you don't get access to the DOM (without explicitly telling it it should be client side).

  • Related