Pagination using Flatlist in React Native (Next/Previous) - react-native

Recently, I've been starting to learn React Native, and I stack with a pagination for my project. I am trying to create a Flatlist which will show only first ten items from data. Then when you click on the next arrow, it will display next different ten items instead of the first ten, and so on. And the same logic to the back arrow but only previous ten items. Here is my code. It works but with some issues. After the first clicking to the next ten items, it shows the same ten, but when you click again, it displays different ten. The back arrow seems that doesn't work properly at all. Could someone help me tweak my code to fix these issues? I will appreciate any help. Thank you!
https://snack.expo.dev/rWq_FLP8o

What you should do is add pageCurrent as a dependency in your useEffect. So every time pageCurrent changes the useEffect runs.
useEffect(() => {
(async () => {
const apiURL = `https://jsonplaceholder.typicode.com/albums?_limit=10&_page=${pageCurrent}`;
fetch(apiURL)
.then((res) => res.json())
.then((resJson) => {
setData(resJson);
});
})();
}, [pageCurrent]); // <-- Makes pageCurrent a dependency
Next make it so when you go back on page 1 it stays on page 1. This way you don't get negative pages or a zero page.
const handlePreviousPage = () => {
console.log("previous page clicked", pageCurrent)
// Do this so your page can't go negative
setpageCurrent(pageCurrent - 1<1?1:pageCurrent - 1)
}
Heres a full example (https://snack.expo.dev/#heytony01/keyboard-function-component-example)

Related

Trigger UseEffect whenever i switch tabs in React Native Tab Navigator

I have implemented react native tab navigator and added 4 screens to it.
I post some record to api in the second screen and i want to have the updated record in the 4th screens where i am getting updated records..
Useeffect only gets targeted only once, and when i put something in it's argument it gives me strange behavior.
I want useeffect to reload and call the api to get latest items in the 4th screen without putting anything in it's arguement(empty argument)
Any help would be highly appreciated.
Try doing this ;
useEffect(() => {
const unsubscribe = navigation.addListener("focus", () => {
makeApiCall();
});
return unsubscribe;
}, [navigation]);
Get navigation in component's arguments(destructuring)
like below;
const My4thTab = ({ navigation }) => {
}
This way useEffect will trigger only once, every time you come on this screen
but make sure to clear the previous state where you store your data, otherwise, there could be a record duplication.
Hope it helps :)

nuxt 3 vue router data fetching and caching

I'm really confused and stuck.
Here is what I think I understand so far in my code below.
PART A: before mounting it's gonna start trying to get datas on the serverside already.
PART B: when mounted on client, wait for datas to be ready, and do masorny layout.
PART C: since it is a component where I list all the datas, when the query changes, it will refresh the data with newly given queries.
Here is what I'm stuck at.
If I go to other page, for example detail page,
and comes back to list page by back and forward button,
no additional data fetching is sent, and scrollBehavior works as expected.
but when I change queries for other results,
then want to do back button to previous query result,
as written clearly in PART C, it fetches data again, saved scroll position is gone.
I'm not getting why in (1) nuxt automatically doesn't fetch same data
and how I should save fetch request and resotre scroll in (2) where I'm navigating within a single component.
const { data: designs, pending, refresh } = useLazyAsyncData('design',
() => fetchDesigns()
) // PART A
onMounted(async () => {
await until(pending).toBe(false).finally(() => masonry()) // PART B
watch(() => useRoute().query, async () => {
window.scrollTo({ top: 0 })
page.value = 1
await refresh()
await until(pending).toBe(false).finally(() => {
masonry()
})
}) // PART C
}

react native navigation screen won't ReRender

when go from category to productList for the first time everything is right but after i came back and try to go for second time list screen won't rerender or refresh what ever you call. is there anyone has suggestions
The list Screen gets data on mount and that's it. If you want it to gets a new data every time the category name changes you have to add it to the useEffect dependencies like so.
const categoryName = navigation.route.params.categoryName;
useEffect(() => {
getData();
},[categoryName]);
Now every time categoryName changes getData gets called.
if you are using tabs just add unmountOnBlur: true, in the <Tab.Screen/> of the screen you are in

React Native: Didn't rerender the component after data was updated

i have two screens one where the profile information is showing and another screen to edit the information. If i entered the first screen profile it's shows me the right data from the database. Then i move to the next screen where i can change the Information everthing worked so far. But if I go back to the previous screen i still see the old data. So there is no rerendering.
But if i navigate to the other screen that screen fetched the new data. and the call getCurrentUserProfile is executed
This ist the screen with the profile information about the user.
const ProfileScreen = props => {
const [userObj, setUserObj] = useState({});
useEffect(() => {
let mounted = true;
getCurrentUserProfile().then(user => {
if (mounted) {
setUserObj(user);
}
console.log(user)
});
return () => mounted = false;
}, []);
console.log("----b------") // This is only output on the first call
}
How can i fix this. Is there a way when in the database is something changed, so the component rerender and fetches the new data.
Thanks.
You are probably using #react-navigation package. So, if you want to refetch data when come back to the previous page, you can use https://reactnavigation.org/docs/use-is-focused on that “previous” page.
Just look at their docs, you will get the idea.
P.S: Usually we don't unmount components directly. In React Native, we use navigator to mount/unmount components

Page does not update after deep link to same page is clicked

I am using React-navigation to handle deep link.
Let's say I am in BusinessProfile Page that is currently displaying detail for BUSINESS B1. I click on home button and minimize my app. When I click on a deep link, myapp://BusinessProfilePage/B2, It takes me to the BusinessProfile Page but still displays result for Business B1. The function to get business detail for B2 is not called.
How can I make the page refresh when a page opens from a deep link.
P.S. I cannot call the function in componentDidUpdate because when the function to get Business Detail is called, it updates the state which then evoke componentDidMount again.
For v5 Use following prop which is alternate to 'key' option in navigate.
getId={({ params }) => params.id}
In this case id will be different. In your case it will be 'B1' and 'B2'. This will create multiple instance of same screen.
You should call your function in a listener for the change event of AppState:
import { AppState } from 'react-native';
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (nextAppState === 'active') { // App has come to the foreground
if(this.state.currentBusiness.ID != (ID received in deep link)) // Need to get data
this.getBusiness(ID received in deep link);
}
};
Taking my best guess here with regards to variable names as you didn't provide any code (you should always include code samples when describing your issue :) ), but you get the idea.