Reputation: 13
I'm making a game for university project. I could not figure out why it's not re-render the screen when I use setState() for status, but it does when I use for fool. If I use console.log(status) It was altered after the setStatus.
const [status, setStatus] = React.useState({ astrounauts: 0, research: 0, money: 0, publicity: 0 });
const [fool, setFool] = React.useState(false);
const acceptCard = (index) => {
let statusAux = status;
statusAux.astrounauts += cards[index].acceptCardStatus.astrounauts;
statusAux.research += cards[index].acceptCardStatus.research;
statusAux.money += cards[index].acceptCardStatus.money;
statusAux.publicity += cards[index].acceptCardStatus.publicity;
//no re-render... =C
setStatus(() => statusAux);
//it does trigger re-render, not working without that.. this is dumb
setFool(() => !fool);
}
...
<View style={styles.cardsOptions}>
<Swiper
cards={cards}
renderCard={(card =>
<Card card={card} />
)}
onSwipedRight={(cardIndex) => acceptCard(cardIndex)}
onSwipedLeft={(cardIndex) => rejectCard(cardIndex)}
// onSwiped={(cardIndex) => { console.log(cardIndex) }}
onSwipedAll={() => { console.log('onSwipedAll') }}
disableBottomSwipe={true}
disableTopSwipe={true}
outputRotationRange={["-10deg", "0deg", "10deg"]}
cardIndex={0}
backgroundColor={'#18191A'}
stackSize={100}
>
</Swiper>
</View>
Upvotes: 1
Views: 33
Reputation: 654
You are setting your state to a function. the setState callback accepts the value itself, not a callback that returns the value. You need to change:
setStatus(() => statusAux);
To:
setStatus(statusAux);
In addition to that... you are mutating the original object, you need to create a new object for React to detect the change. You can do using the spread operator like this:
let statusAux = {...status};
Upvotes: 1
Reputation: 607
Just try to do this, Don`t need to use "()=>"
const acceptCard = (index) => {
let statusAux = status;
statusAux.astrounauts += cards[index].acceptCardStatus.astrounauts;
statusAux.research += cards[index].acceptCardStatus.research;
statusAux.money += cards[index].acceptCardStatus.money;
statusAux.publicity += cards[index].acceptCardStatus.publicity;
//no re-render... =C
setStatus(statusAux);
//it does trigger re-render, not working without that.. this is dumb
setFool(!fool);
}
Upvotes: 0