React Native Redux and redux-axios-middleware example
Install expo cli if it’s not yet installed.
npm install -g expo-cli
Initialize a project.
expo init reactNativeReduxExampleGithub
Install dependencies to the project.
yarn add axios redux-axios-middleware redux react-redux
reducer.js, defines the action types, reducer, and actions.
// https://github.com/svrcekmichal/redux-axios-middleware // Every action which have payload.request defined will be handled by middleware. There are two possible type definitions. // use action.type with string name // action with type will be dispatched on start, and then followed by type suffixed with underscore and // success suffix on success, or error suffix on error // defaults: success suffix = "_SUCCESS" error suffix = "_FAIL" export const GET_ACCOUNT = 'google/LOAD'; export const GET_ACCOUNT_SUCCESS = 'google/LOAD_SUCCESS'; export const GET_ACCOUNT_FAIL = 'google/LOAD_FAIL'; export default function reducer(state = { account: {} }, action) { switch (action.type) { case GET_ACCOUNT: return { ...state, loading: true }; case GET_ACCOUNT_SUCCESS: console.log('reducer action.payload: ' + JSON.stringify(action.payload)); return { ...state, loading: false, account: action.payload.data }; case GET_ACCOUNT_FAIL: return { ...state, loading: false, error: 'Error while fetching account' }; default: return state; } } // When we call the accountInfo function, the action GET_ACCOUNT is dispatched with a payload.request content. // The redux-axios-middleware intercepts this action and eventually make an HTTP request to the GitHub API. // After that, it will, automatically, dispatch either a GET_ACCOUNT_SUCCESS or a GET_ACCOUNT_FAIL action, // depending on the status of the request. If you look at the reducer function, you see that we are returning // a new state based on all the dispatched actions, being the most important the GET_ACCOUNT_SUCCCESS where we // extract the account info from the action.payload (response from the API). export function accountInfo(user) { return { type: GET_ACCOUNT, payload: { request: { url: `/users/${user}` } } }; }
GitAccount.js, the view component, sends action and displays result.
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { connect } from 'react-redux'; import { accountInfo } from './reducer'; class GitAccount extends Component { componentDidMount() { console.log("componentDidMount props: " + JSON.stringify(this.props)); console.log("componentDidMount state: " + JSON.stringify(this.state)); // initiates the function call defined in the reducer this.props.accountInfo('google'); } render() { console.log("render props: " + JSON.stringify(this.props)); console.log("render state: " + JSON.stringify(this.state)); const { account } = this.props; return (); } } const styles = StyleSheet.create({ container: { flex: 1, margin: 16, } }); // Map the state of the redux store to the component props. const mapStateToProps = state => { console.log("mapStateToProps state: " + JSON.stringify(state)); let storedAccount = {...state.account};// { key: state.account.id, ...state.account }; return { account: storedAccount }; }; // Map the dispatched actions to the component props. // This makes the function call 'this.props.accountInfo('google')' in componentDidMount possible. const mapDispatchToProps = { accountInfo }; // currying function https://blog.benestudio.co/currying-in-javascript-es6-540d2ad09400 export default connect(mapStateToProps, mapDispatchToProps)(GitAccount); {JSON.stringify(account)}
App.js, initializes the app with redux and everything.
import axios from 'axios'; import React, { Component } from 'react'; import { StyleSheet, View } from 'react-native'; import { Provider } from 'react-redux'; import { applyMiddleware, createStore } from 'redux'; import axiosMiddleware from 'redux-axios-middleware'; import GitAccount from './GitAccount'; import reducer from './reducer'; // axios api client const client = axios.create({ baseURL: 'https://api.github.com', responseType: 'json' }); // initializes axios api client with axiosMiddleware and create redux store with reducer. const store = createStore(reducer, applyMiddleware(axiosMiddleware(client))); export default class App extends Component { render() { return ( // Provider is a wrapper to the application and responsible for providing access to the created store); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', marginTop: 50 } });
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts