My useEffect method is:
useEffect(() => {
async function getRoomDetails(){
const db = getFirestore();
const querySnapshot = await getDocs(collection(db, "rooms"));
querySnapshot.forEach((doc)=>{
console.log('Document');
console.log(doc.id);
console.log(doc.data().name);
var channelNameData = doc.data().name;
})
}
async function getRoomMessages() {
const db = getFirestore();
const roomMessages =
roomId &&
query(
collection(db, "rooms", roomId, "messages"),
orderBy("timestamp", "asc")
);
const querySnapShot = await getDocs(roomMessages);
querySnapShot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
});
}
getRoomDetails();
getRoomMessages();
}, []);
and I want to pass channelNameData to ChatInput, as
<ChatInput
channelName={channelNameData}
channelId={roomId}
/>
How do I do this? I also want to avoid Assignments to the 'channelNameData' variable from inside React Hook useEffect will be lost after each render error.
Create a state variable with useState.
Modify that variable inside your useEffect hook.
The variable will then be in scope for the rest of your component and you can pass it as a prop.
Make sure you handle the default state from before the effect hook has run (e.g. with a sane default value or a value that indicates a <Loading /> component should be rendered instead of <ChatInput />)
You can utilize the useState hook to create a variable for storing channelNameData.
import { useState } from 'react';
const [channelNameDataState, setChannelNameDataState] = useState(null)
Inside your useEffect, you can have a line that sets channelNameDataState.
setChannelNameDataState(channelNameData)
Then you would pass in this state to the child component
<ChatInput
channelName={channelNameDataState}
channelId={roomId}
/>
As for preventing assignments to the channelNameData variable getting lost, you should be able to combine the useState hook with localState to make sure you can persist state.
Create state variable and assign value inside the effect,
const [channelNameData, setChannelNameData] = useState([]);
useEffect(() => {
async function getRoomDetails(){
const db = getFirestore();
const querySnapshot = await getDocs(collection(db, "rooms"));
querySnapshot.forEach((doc)=>{
console.log('Document');
console.log(doc.id);
console.log(doc.data().name);
//var channelNameData = doc.data().name;
setChannelNameData(doc.data().name)
})
}
async function getRoomMessages() {
const db = getFirestore();
const roomMessages =
roomId &&
query(
collection(db, "rooms", roomId, "messages"),
orderBy("timestamp", "asc")
);
const querySnapShot = await getDocs(roomMessages);
querySnapShot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
});
}
getRoomDetails();
getRoomMessages();
}, []);
in jsx,
<ChatInput
channelName={channelNameDataState}
channelId={roomId}
/>