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

233
Views
React: Cannot get state slice to update, but other state properties work fine

Using these two pieces of state:

this.markerArray = [];
this.arrayLength = 0;

I am trying to use this function:

getMarkers = () => {
  this.dbRef.get().then((snapshot) => {
    snapshot.docs.forEach((marker) => {
      if (!this.markerArray.includes(marker.id)) {
        let currentID = marker.id;
        let appObj = {
          ...marker.data(),
          ["id"]: currentID,
        };
        this.markerArray.push(appObj);
      }
    });

    this.setState({
      markerArray: this.markerArray,
    });
    // (problem code) this.setState({arrayLength: this.markerArray.length})

    return this.markerArray;
  });
};

To update a list of map markers. I am trying to update this.arrayLength when this.markerArray's length changes. I think the problem has to do with setState's asynchronous nature, but I can't figure out what to do with that information.

I have tried:

  1. Creating a separate function to set arrayLength
  2. Passing that function as a callback when setting markerArray's state
  3. Calling the function in Render (infinite loop)
  4. Setting arrayLength in the same setState as markerArray
  5. Changing the initial value of arrayLength to null, 0, and ''

I have even tried setting arrayLength to an arbitrary number that does not rely on markerArray.length, but it won't update.

about 4 years ago · Juan Pablo Isaza
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!