I'm creating a login with Axios in react native, but when adding the dispatch it does not change state and leaves it in 'checking'and ignores the back and logs everyone even whiout data on inputs. Create my context, reducer and authInicialState but nothing.
I need to do something else o what am I doing wrong?
On terminal {"errorMessage": "", "status": "checking", "token": null, "user": null}
Context
type AuthContextProps ={
errorMessage: string;
token: string | null;
user: Data | null;
status: 'checking' | 'authenticated' | 'no-authenticated';
signIn: (loginData: LoginData) => void;
}
const authInicialState: AuthState ={
status: 'checking',
token: null,
user: null,
errorMessage: ''
}
export const AuthContext = createContext ({} as AuthContextProps);
export const AuthProvider = ({children}: any) =>{
const [state, dispatch] = useReducer ( authReducer, authInicialState);
const signIn = async ({email, password}: LoginData) => {
try {
const resp = await loginApi.post <LoginResponse>('/login', {email, password});
console.log(resp.data);
dispatch ({
type: 'signUp',
payload:{
user: resp.data.usuario,
token: resp.data.token
}
})
};
return(
<AuthContext.Provider value= {{
...state,
signUp,
signIn,
}}>
{children}
</AuthContext.Provider>
)
}
Reducer
export interface AuthState {
status: 'checking' | 'authenticated' | 'no-authenticated';
token: string | null;
errorMessage: string;
user: Data | null;
}
type AuthAction =
| {type: 'signUp', payload: {token: string, user: Data}}
| {type: 'addError', payload: string}
export const authReducer = (state: AuthState, action: AuthAction ): AuthState => {
switch (action.type) {
case 'signUp':
console.log('estado', state)
return{
...state,
errorMessage: '',
status: 'authenticated',
token: action.payload.token,
user: action.payload.user
};
default:
return state;
}
}