i try to create a Login Screen with the Auth function and navigation in a seperate file but i always get an error by the navigation. I tried to pass props but it dont work...
Can you please help me?
This is my code:
App.js
export default class App extends React.Component{
render(){
return(
<RootStack navigation={this.props.navigation} />
)
}
}
rootstack.js
const StackNavigator = createStackNavigator({
Login: {
screen: login,
navigationOptions: {
headerShown: false,
}
},
Home: {
screen: TaskScreen,
navigationOptions: {
headerShown: false,
}
}
})
export default createAppContainer(StackNavigator);
Login.js
...
<Auth props={this.props}/>
...
auth.js
export function Auth() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const auth = (props) => {
fetch('http://192.168.178.26:8000/auth/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password })
})
.then(res => res.json())
.then(res => {
saveToken(res.token);
console.log(res.token);
props.navigation.navigate('Home'); # Here i get the error
})
.catch(error => console.log(error));
};
const saveToken = async (token) => {
await AsyncStorage.setItem('IN_Token', token)
};
...
Can you please help me?
Oh sorry, i forgot to add the Error Message: undefined is not an object (evaluating 'props.navigation.navigate')
As you are using function component you should pass the props
as params to the function component to access them
So, in your auth.js
just send props
in the params of the function
export function Auth(props) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const auth = (props) => {
fetch('http://192.168.178.26:8000/auth/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password })
})
.then(res => res.json())
.then(res => {
saveToken(res.token);
console.log(res.token);
props.props.navigation.navigate('Home'); # Here i get the error
})
.catch(error => console.log(error));
};
const saveToken = async (token) => {
await AsyncStorage.setItem('IN_Token', token)
};
or
const auth = ({props}) => {
...
.then(res => res.json())
.then(res => {
saveToken(res.token);
console.log(res.token);
props.navigation.navigate('Home'); # Here i get the error
})
This should work!