'State not updating using setState hook
setBlock is not updating block with the new values I submit to blockTitle and blockDuration (which are working btw).
export default function App() {
const [blockTitle, setBlockTitle] = useState();
const [blockDuration, setBlocksDuration] = useState();
const [block, setBlock] = useState({title: '', duration: ''});
const [blocksList, setBlocksList] = useState([{title: 'test', duration: '2h'}]);
const handleAddBlock = () => {
console.log(blockTitle);
console.log(blockDuration);
console.log(block);
//setBlock({title: blockTitle, duration: blockDuration})
setBlocksList([...blocksList, block]);
console.log(block);
//setBlockTitle('');
//setBlocksDuration('');
//setBlock();
}
Here are the input components that update the state of the mentioned above variables:
<TextInput style={styles.input} placeholder={'Insert block title'} value={blockTitle} onChangeText={text => setBlockTitle(text)} />
<TextInput style={styles.input} placeholder={'Insert block duration'} value={blockDuration} onChangeText={duration => setBlocksDuration(duration)} />
</KeyboardAvoidingView>
Here's the button to push to update to update the block:
<TouchableOpacity style={styles.buttonContainer} onPress={() => { setBlock({title: blockTitle, duration: blockDuration}); console.log(block); handleAddBlock(); }}>
I tried submitting default values (not based on those variables) but it's also not working. Tried also to do the setBlock elsewhere, in case it was a problem of asynchronicity. What am I doing wrong? Thanks in advance.
Solution 1:[1]
The setBlocksList is async and therefore you cannot see the updates immediately. To see the updated values move the console.log outside of handleAddBlock.
const handleAddBlock = () => {
setBlocksList([...blocksList, block]);
};
console.log(blocksList);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amila Senadheera |
