Reputation: 133
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')
Upvotes: 0
Views: 54
Reputation: 31
you are not getting the props in the top of the Auth component, you need to get the props in the declaration, not on the function above.
you should declare Auth like this export function Auth(props)
Another thing is: you are passing Auth props={this.props}
so your props object inside Auth probably is something like this: props.props.navigation
. You can use spread operator to avoid this <Auth {...this.props}/>
This should work.
Another approach you can do and i like more is the Auth function returns a callback to Login.js
and inside Login.js you do the navigation.
Upvotes: 0
Reputation: 1491
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!
Upvotes: 1