I am new to React Native and Axios, I am trying to build an Authentication System, my API (Created in Laravel) is working well in Postman, when I come to test the whole application and try to login, I am getting this error:
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'error.response.data')]
* src\AuthProvider.js:36:36 in axios.post.then._catch$argument_0
- node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
- node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
I am using my Android phone for testing, here is may code:
axios.defaults.baseURL = 'http://localhost:8000';
export const AuthContext = React.createContext({});
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
return (
<AuthContext.Provider
value={{
user,
setUser,
error,
setError,
login: (email, password) => {
axios.post('/api/sanctum/token', {
email,
password,
device_name: 'mobile',
})
.then(response => {
const userResponse = {
email: response.data.user.email,
token: response.data.token,
};
setUser(userResponse);
SecureStore.setItemAsync('user', JSON.stringify(userResponse));
})
.catch(error => {
// const key = Object.keys(error.response.data.errors)[0];
// setError(error.response.data.errors[key][0]);
console.log(error);
});
},
logout: () => {
axios.defaults.headers.common['Authorization'] = `Bearer ${user.token}`;
axios.post('/api/logout')
.then(response => {
setUser(null);
SecureStore.deleteItemAsync('user');
})
.catch(error => {
console.log(error.response);
});
}
}}>
{children}
</AuthContext.Provider>
);
}