I have a functional react component Tasks_1, and initially, I want to retrieve the userId from the redux store which successfully works.
After this, I want to use the userId in useEffect that I retrieved from the redux store to get data from the backend.
When useEffect runs it says there is an empty string retrieved from the state id. How can I make useEffect run after the state "id" is set from useState retrieving it from the store?
function Tasks_1 () {
const [id, setId] = useState('');
const userId = useSelector((state) => state.id);
const [tasks, setTasks] = useState([]);
useEffect(() => {
setId(userId);
if (id !== '') {
db.collection('users').doc(id).collection('tasks').onSnapshot((snapshot)=>{
const tempTasks = [];
snapshot.forEach(
doc => {
tempTasks.push(doc.data());
}
)
setTasks(tempTasks);
});
}
}),[id];
return (
...
)
}
You might get an infinite loop if you do get this to work the way you have it. Updating id using setId will cause a re-render and the useEffect will be called again since you changed id and so on....
I believe this would work:
const [id, setId] = useState('');
const userId = useSelector((state) => state.id);
const [tasks, setTasks] = useState([]);
useEffect(() => {
// this will make sure you only set id when userId
// is a valid value, and it won't reset it every
// serenader
if(userId!=='' && id !== userId)
setId(userId);
if (id !== '') {
db.collection('users').doc(id).collection('tasks').onSnapshot((snapshot)=>{
const tempTasks = [];
snapshot.forEach(
doc => {
tempTasks.push(doc.data());
}
)
setTasks(tempTasks);
});
}
}, [id, userId]);
and you would have to add userId to the array dependencies.