In my React Native application, i am changing data on previous and next button. Now i have a function called getImageChunked where i'm setting the data on state. But on pressing previous button and next button data doesn't change instantly on those button press functions. Instead in button press functions, it shows the previous state data. Here's my current code :
const [imageSet, setImage] = useState([]);
const [count, setCount] = useState(0);
const [nextImage, setNextImage] = useState(false);
const [prevImage, setPrevImage] = useState(false);
useEffect(() => {
getImageChunked();
},[]);
nextButton = () =>{
setCount(count + 1);
getImageChunked(count + 1);
console.log('imageset',imageSet) // It shows previous state data
if (props.imageset === []){
setNextImage(true);
}
}
prevButton = () =>{
setCount(count - 1);
getImageChunked(count - 1);
console.log('imageset',imageSet) // It shows previous state data
if (props.imageset === []){
setPrevImage(true);
}
}
getImageChunked = (n) =>{
var perChunk = 4
var result = 'API Data'
var merged = [].concat.apply([], result[n === undefined ? 0 : n]);
console.log('merged',merged); // Here the data changes properly
setImage(merged);
}
How i can get instant changed state data on prevButton and nextButton press functions?
From what I understand, React will queue actions and then execute them in batches at a later time, which can cause these types of lagging state issues
One way to deal with this, is to watch your state with useEffect.
useEffect(() => {
getImageChunked()
}, [count])
This way, getImageChunked() will only be called after your count state has updated
I would suggest following:
const [imageSet, setImage] = useState([]);
const [count, setCount] = useState(0);
const [nextImage, setNextImage] = useState(false);
const [prevImage, setPrevImage] = useState(false);
useEffect(() => {
getImageChunked();
},[count]); // Each time count is changing getImageChunked got called
nextButton = () =>{
setCount(count + 1);
if (Array.isArray(props.imageset)){ // AFAIK props.imageset === [] is always false
setNextImage(true);
}
}
prevButton = () =>{
setCount(count - 1);
if (Array.isArray(props.imageset)){
setPrevImage(true);
}
}
getImageChunked = () =>{
var perChunk = 4
var result = 'API Data'
var merged = [].concat.apply([], result[count]);
console.log('merged',merged); // Here the data changes properly
setImage(merged);
}