Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
Delay useEffect until useSelector retrieves data from the Redux store in React Native

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 (
        ...

   )

 }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!