0

I would be thankful if someone could point me into a right direction in understanding the Redux architecture.

I should implement "reducer" functions that will handle my actions. Reducer functions should be combined and create a store.

Lets say I have a LoginForm (React) component, that makes a XHR request to backend API, and receives a JWT token in response.

When I get the response from the API I should dispatch an action like:

store.dispatch({type: "USER_LOGGED_IN",
                payload: {username: "john", JWT: "..."});

This updates the state of my application.

What next?

How do I route to to next page? How do I rerender my components (like navbar, etc.) with the logged in username?

Do I use listeners for that?

user2449761
  • 1,169
  • 13
  • 25

2 Answers2

1

Let's say you've a method to authorize user:

import { browserHistory } from 'react-router';

// ...

function promisedApiCall(inputData) {
    // ...
    // api request to backend with input data
    // return a promise
}

/*
 * on form submit we call this with input data
 */
function authorizeUser(inputData) {
   return promisedApiCall(inputData)
       .then((response) => store.dispatch({
           type: "USER_LOGGED_IN",
           payload: {
               username: response.userName,
               JWT: response.JWT
           }
       }))
       .then(() => browserHistory.push('/success/path/url'))
       .catch(() => browserHistory.push('/failure/path/url'));
}

Assuming you have the following prerequisites:

  • Created redux store and store object is available in the scope where authorizeUser() is executed.
  • The method promisedApiCall is the function which makes the request to backend with input data from LoginForm.
  • promisedApiCall should return a promise. [this is really important]
  • Configured react-router with redux

Once this is complete, app state is updated with user info and also user will be redirected to a new page. This post explains more about programmatically redirecting using react-router.

Access you app state in you component using Redux connect.

Now you have the user info in your component as props.

Community
  • 1
  • 1
yadhu
  • 15,423
  • 7
  • 32
  • 49
0

react-router has a component browserHistory.You can import that like this,

import {browserHistory} from 'react-router';

And to change your route,

browserHistory.push(<route_where_you want_to_go>);

This will let you change the route.

Vishal Sharma
  • 2,550
  • 1
  • 23
  • 40
  • yes this is clear for me. It is not clear how were should I place this snippet? How does my application react to state change? – user2449761 Nov 27 '16 at 09:11