简体   繁体   中英

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?

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])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM