javascript - fetch should not be in the action || reducer? -


  1. i'm doing right if put fetch in componentdidmount ()? folly put fetch action or reducer?
  2. why {this.props.data.name} not work without setting of standard parameters data in reducer? without (state = {data: { }}, action)?!

reducer

const reducer = (state = {   data: {    } }, action) => {   switch (action.type) {     case 'experiment':       return {         ...state,         data: action.data       }       break     default:       return state   } }  export default reducer 

component

import react, { component } 'react'  import { connect } 'react-redux'  class persistent extends component {   componentdidmount () {     fetch('https://api.github.com/users/reactjs').then((response) => {       response.json().then((json) => {         this.props.dispatch({           type: 'experiment',           data: json         })       })     })   }   render () {     return (       <div>         <ol>           <li>{this.props.data.name}</li>           <li>{this.props.data.url}</li>         </ol>       </div>     )   } }  export default connect(   (state) => {     return {       data: state.data     }   } )(persistent) 

use redux-thunk middleware. allows action creators return functions instead of action objects. functions chained final dispatch of action object.

while creating store, include middleware follows:

import { createstore, applymiddleware } 'redux'; import thunkmiddleware 'redux-thunk'; import createlogger 'redux-logger'; import rootreducer '../reducers/rootreducer';  const loggermiddleware = createlogger();  export function configurestore(initialstate) {   return createstore(     rootreducer,     initialstate,     applymiddleware(       thunkmiddleware,       loggermiddleware     )); } 

an example of action creator uses thunk middleware:

getcards(email, token) {     return (dispatch, getstore) => {       dispatch(cardactions.getcardsrequest(email));       fetch(apiurls.getcardsurl + email, {         method: 'get',         headers: {           'accept': 'application/json',           'content-type': 'application/json',           'api-key': token,         },       })       .then(response => {         return response.json().then(responsejson => {           return dispatch(cardactions.getcardsresponse(responsejson.postcards, response.status));         });       })       .catch(err => {         console.error(err);       });     };   } 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -