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

83
Views
React Native State not updating with an empty Array

Hi stackoverflow people I know this has been asked about a million times. However I don't think I have found an answer to my problem!

Long story short I am updating a state in my react native app only if a statement is true. What I am experiencing is this state not being updated somehow.

const emptyArray = []
const [collapsed, setCollapsed] = useState(true);
const [selectedGem, setSelectedGem] = useState(false);
const [usedGem, setUsedGem] = useState(emptyArray);
const [selectedPropType, setSelectedPropType] = useState('all');

const randomItem = (items) => {
    return items[Math.floor(Math.random()*items.length)];
}

const getRandomQuestion = () => {
    let selectableGems = gems

    const maxGems = selectableGems.length;
    let tempGems = [];

    if(usedGem.length >= maxGems) {
        setUsedGem(emptyArray)
    }

    for (let i=0; i<maxGems; i++)
    {
        if(usedGem.length === 0 || usedGem.find(gem => gem === i) === undefined) {
            tempGems.push(i)
        }
    }

    const randomGemNumber = randomItem(tempGems)

    setUsedGem([...usedGem, randomGemNumber])

    setSelectedGem(selectableGems[randomGemNumber])
}

Basically if(usedGem.length >= maxGems) {happens only when all the gems have been randomised once (there are 130 item in the gems variable). I'd expect then the usedGem to be empty in the for but this isn't the case.

I have tried a few solutions I found without luck. I know this has to do with async but I can't figure it out! Anyone could help me please?

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

0

Here this might help. The thing is you can't get instant update after setting state

const getRandomQuestion = () => {
let selectableGems = gems

const maxGems = selectableGems.length;
let tempGems = [];
let gems = Array.from(usedGem);

if(gems.length >= maxGems) {
    gems = []
}

for (let i=0; i<maxGems; i++)
{
    if(gems.length === 0 || gems.find(gem => gem === i) === undefined) {
        tempGems.push(i)
    }
}

const randomGemNumber = randomItem(tempGems)

setUsedGem([...gems, randomGemNumber])

setSelectedGem(selectableGems[randomGemNumber])
}
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!