I have react native expo web app. And I try to go to the previous screen. The problem I am facing is that there is one main screen. And a subcategory screen with has a one-to-one relationship. Fore example you have mammals(main screen) and then you have dogs –> bulldogs –> English bulldog.
And the user is on bulldogs and what to go back to dogs. Then the
goBack()
doesn’t work. Because then the user goes back to the mainscreen(mammals).
So I try it like this:
import { useNavigation, useNavigationState } from "@react-navigation/native";
export const SubCategoryScreen = ({ route, navigation }) => {
const routes = useNavigationState((state) => state.routes);
const previousRoute = routes.length > 1 ? routes[routes.length - 2].name : null;
}
and then the back button:
<Button
title="go back"
onPress={() => {
navigation.navigate(previousRoute);
console.log(previousRoute);
}}>
back
</Button>
But this doesn’t work. The user goes anyway back to mainscreen. And not the previous screen.
The api call for the subcategories looks like:
export const fetchSubCategoryData = async (id) => {
const token = await retrieveToken();
try {
if (token) {
const response = await fetch(`${API_URL}/api/categories/${id}/`, {
method: "GET",
headers: {
Authorization: `Token ${token}`,
"Content-Type": "application/json",
},
});
//console.log(response);
return await response.json();
} else {
throw new Error(token);
}
} catch (error) {
Error("can't retrieve data");
}
};
And the url of a subcategory looks:
http://127.0.0.1:8000/api/categories/13/
Question: How to go to previous screen within the same component: SubCategoryScreen?