'React Native - Header & Accessing State
I'm trying to have a header button in my screen that access the screen state and validates if a post is ready to send to the DB (ie. its not an empty string and if theres an image post the image too).
When i create a full post (image and text) and try and fire the post function in the screen, it works (see the 'test' button on the screen)
When i create a full post (image and text) and try and fire the post function from the header, it does not grab the state properly.
What is happening here? How do i resolve this?
Screen State & Header
function PostScreen(props) {
const [newPost, setNewPost] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [mediaAsset, setMediaAsset] = useState('')
React.useLayoutEffect(() => {
props.navigation.setOptions({
headerRight: () => {
return (
isLoading ? <ActivityIndicator color='#4292CE' size='small' style={{ marginRight: 10 }} /> :
<TouchableOpacity style={styles.postButton} onPress={() => postFunction()}>
<Text style={styles.postText}>Post</Text>
</TouchableOpacity>)
},
title: null
});
}, [isLoading, newPost]);
Post Function
let postFunction = async () => {
setIsLoading(true)
if (newPost === '') {
console.log(newPost) // this comes up as nothing when the postFunction is executed from the header
}
else if (mediaAsset === '') {
//! post only the text
}
else if (mediaAsset != ''){
//! post the text and the image
}
setIsLoading(false)
}
Test Environment
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

