I am currently creating a log in page that makes a POST request to an API when the user enters their details (A Post request containing the users details will be sent to the server). If this request is successful (Server responds with status 200 and sends back an access token giving the user access to the full API) the user should be routed towards another page. Below you can see the code that deals with the API call and then what should be done when the server response status is 200:
api.authorise(email, password, appid).then((result) => {
if (result.status === 200) {
console.log("Auth Successful");
successfulAuth = true;
<ProjectSelect api={api} data={response.data} />;
return result;
} else {
console.log("Auth Failed")
return result;
}
As you can see above, if the user credentials are valid, I want the user to be routed to the 'ProjectSelect' page with the relevant props. However, with the current code, after the user has successfully logged in nothing changes. I have tried using 'useNavigate' like this:
const nav = useNavigate()
api.authorise(email, password, appid).then((result) => {
if (result.status === 200) {
console.log("Auth Successful");
successfulAuth = true;
nav("/projectselect");
return result;
} else {
console.log("Auth Failed")
return result;
}
But then I cannot pass the 'api' and 'data' props to the 'ProjectSelect' component. I would like to know why the call to the project select component is not working or a better solution to this problem. Thanks in advance.
CodePudding user response:
If you are using React Navigator, then catch this: https://reactnavigation.org/docs/params/
There is no problem with passing params to the useNavigate()
after the route, all of them should be available in the children component under the params
property of the route
props destructured in the functional component declaration, as it is described in the docs.
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
/* 1. Navigate to the Details route with params */
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
function DetailsScreen({ route, navigation }) {
/* 2. Get the param */
const { itemId, otherParam } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}</Text>
<Button
title="Go to Details... again"
onPress={() =>
navigation.push('Details', {
itemId: Math.floor(Math.random() * 100),
})
}
/>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
);
}