Defining actions and the reducer

Before getting into the details, let's see the reducer and actions we'll have. The former is quite simple, since basically all we care about is having a token and a logging flag:

// Source file: src/routingApp/login.reducer.js

/* @flow */

import {
LOGIN_REQUEST,
LOGIN_SUCCESS,
LOGIN_FAILURE
} from "./login.actions";

export const reducer = (
state: object = {
// initial state
logging: false,
token: ""
},
action
) => {
switch (action.type) {
case LOGIN_REQUEST:
return {
...state,
logging: true,
token: ""
};

case LOGIN_SUCCESS:
return {
...state,
logging: false,
token: action.token
};

case LOGIN_FAILURE:
return {
...state,
logging: false
};

default:
return state;
}
};

We will have some action creators that will help us understand the rest. The important one is attemptLogin() that tries connecting to the server, and if successful stores the token that will mark that the user is logged in:

// Source file: src/routingApp/login.actions.js

/* @flow */

import { loginService } from "./serviceApi";

export const LOGIN_REQUEST = "login:request";
export const LOGIN_SUCCESS = "login:success";
export const LOGIN_FAILURE = "login:failure";

export const loginRequest = () => ({
type: LOGIN_REQUEST
});

export const loginSuccess = (token: string) => ({
type: LOGIN_SUCCESS,
token
});

export const loginFailure = () => ({
type: LOGIN_FAILURE
});

// Complex actions:

export const attemptLogin = (
user: string,
password: string
) => async dispatch => {
try {
dispatch(loginRequest());
// the next line delays execution for 5 seconds:
// await new Promise(resolve => setTimeout(resolve, 5000));
const result = await loginService(user, password);
dispatch(loginSuccess(result.data));
} catch (e) {
dispatch(loginFailure());
}
};
We'll leave it as an exercise to you to write a <LogOut> component that will provide a button, which when clicked will just call an action to delete the current token.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset