I am working in React Native and have encountered this numerous times, and it is extremely frustrating, and I know there has to be an easier solution that the hoops I've been jumping through.
Essentially whenever I have something like this
const [arrayState, setArrayState] = useState(false)
// OR //
const [arrayState, setArrayState] = useState([])
if I have a function that adds something to that array, it will not work on the first firing of that function, but will work subsequently. For example, the latest instance of this is when I am attempting to append image uri's to an initially empty local state array.
const [images, setImages] = useState(false)
// I have also tried '' '' = useState([]) //
// Other Code //
const handleClickTakePicture = async () => {
const r = await takePhoto()
if (!r.cancelled) {
if (!images){
console.log("Should set images to ", [r.uri])
let temp = [r.uri]
setImages(temp)
}
else{
setImages([...images, r.uri])
changeFunction({
...changeValue,
specific_pictures: images
})
}
}
}
If I click the 'take picture' button 5 times, four picture uri's will be added the the images
array. If I click it once, nothing will.
Why is this? I've noticed it can have similar issues when changing or setting hashes
EDIT: Added takePhoto
function
const takePhoto = async () => {
if (cameraRef) {
try {
let photo = await cameraRef.current.takePictureAsync({
allowsEditing: true,
aspect: [4, 3],
// base64: true,
quality: 1
})
return photo
} catch (error) {
console.log(error)
}
}
}
CodePudding user response:
useState
is an async function, meaning the state change will not be reflected immediately.
Instead, you can run the function everytime setImages
is done with updating.
useEffect(()=>{
changeFunction({
...changeValue,
specific_pictures: images
})
}, [images]);
CodePudding user response:
...
else{
setImages([...images, r.uri])
changeFunction({
...changeValue,
specific_pictures: [...images, r.uri] //fix here
})
}
...
Keep in mind the second parameter of useState is an asynchronous function, setImages([...images, r.uri])
will be called before changeFunction
but it will execute after changeFunction
.
More details: How JavaScript works