Issue
I am trying to use the username from the firebase and create a user in the FirepadUserList. The code looks like this
import { useRef, useEffect,useState } from 'react';
import 'codemirror/lib/codemirror.css'
import CodeMirror from 'codemirror';
import firebase from "firebase/compat";
import 'firepad/dist/firepad.css'
import classes from './Document.module.scss'
import './editor.css';
import FirepadUserList from '../../components/UserList/firepad-userlist';
import '../../components/UserList/firepad-userlist.css'
import Loading from '../../components/Loading';
import {useSession} from "../../firebase/AuthProvider";
type User = firebase.User | null;
type Loading = boolean;
function Editor() {
const {user, loading} = useSession();
const username = user?.displayName;
const editorRef = useRef<HTMLDivElement>(null);
let userId = Math.floor((Math.random() * 10) + 1);
useEffect(() => {
const codeMirror = CodeMirror(editorRef.current!, { lineWrapping: true });
window.CodeMirror = CodeMirror;
const Firepad = require('firepad');
const firepadRef = getExampleRef();
const firepad = Firepad.fromCodeMirror(firepadRef, codeMirror,
{ richTextToolbar: true, richTextShortcuts: true, userId:userId.toString()});
FirepadUserList.fromDiv(firepadRef.child('users'),
document.getElementById('userlist'), userId.toString(),username);
firepad.on('ready', function () {
if (firepad.isHistoryEmpty()) {
firepad.setHtml("<div>Start typing</div>");
}
});
}, [username]);
function getExampleRef() {
let ref = firebase.database().ref();
const hash = window.location.hash.replace(/#/g, '');
if (hash) {
ref = ref.child(hash);
} else {
ref = ref.push(); // generate unique location.
window.location.href = window.location + '#' + ref.key;
}
if (typeof console !== 'undefined') {
console.log('Firebase data: ', ref.toString());
}
return ref;
}
return (
<>
<div id="userlist" className={classes.userlist}></div>
<div className={classes.editor} ref={editorRef}></div>
</>
);
}
export default Editor;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
But if I use username variable in the useEffect both the codeMirror editor and FirepadUserList render two times and another user is shown online where it should be only one 
but if the hardcode the username with string as like username = "Fahim Khan" everything works fine. Note I am using .tsx extension.
Solution
okay I got the answer. The problem was the delay in fetching the username. so the useEffect was running two times. if the wrap the code inside useEffect inside the condition if(username != null) it works fine
Answered By - Fahim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.