Saltar al contenido

usando redux thunk vs axios en el ejemplo de código de componente de reacción

Posterior a de una extensa compilación de información pudimos solucionar este atascamiento que suelen tener muchos lectores. Te ofrecemos la solución y nuestro deseo es servirte de mucha ayuda.

Ejemplo 1: datos de recuperación de redux usando axios

// action typeconstFETCH_ALL="FETCH_ALL";constFETCH_FAIL="FETCH_FAIL";// initial stateconst fetchState =
  users:[],
  error:"";//action creatorconstfetchDataAsync=()=>return(dispatch)=>
    axios
      .get("https://jsonplaceholder.typicode.com/users").then(( data )=>dispatch( type:FETCH_ALL, users: data )).catch((err)=>dispatch( type:FETCH_FAIL, error: err ));;;// reducerconstfetchReducer=(state = fetchState, action)=>switch(action.type)caseFETCH_ALL:return action.users;caseFETCH_FAIL:return...state, error: action.error;default:return state.users;;// storeconst reducers =combineReducers( users: fetchReducer );const store =createStore(reducers,applyMiddleware(logger, thunk));//fetchAllData componentimportReact, useEffect from"react";import connect, useDispatch from"react-redux";import fetchDataAsync from"../redux/Action";constFetchData=(props)=>const dispatch =useDispatch();useEffect(()=>dispatch(fetchDataAsync());,[]);return(<><ul>user.email</li>))</ul></>);;constmapStateToProps=(state)=>return...state ;;exportdefaultconnect(mapStateToProps)(FetchData);

Ejemplo 2: recuperar datos de redux saga usando axios

//EXAMPLE FETCH DATA API REDUX SAGA// USER ACTION CREATORexportconstREQUEST_API_DATA='REQUEST_API_DATA'exportconstRECEIVE_API_DATA='RECEIVE_API_DATA'exportconstrequestApiData=()=>( type:REQUEST_API_DATA)// USER REDUCERimportREQUEST_API_DATA,RECEIVE_API_DATAfrom'../actions/user'exportdefault(state =, type, payload )=>switch(type)caseRECEIVE_API_DATA:return payload.usersdefault:return state
  // USER SAGAimportaxiosfrom'axios'import call, put, takeEvery, takeLatest from'redux-saga/effects'importREQUEST_API_DATA,RECEIVE_API_DATAfrom'./actions/user'function*userReceiveAll(action)tryconst data =yieldcall(axios.get,'https://jsonplaceholder.typicode.com/users')yieldput( type:RECEIVE_API_DATA, payload: users: data )catch(e)console.log(e.message)exportdefaultfunction*userSendAll()yieldtakeLatest(REQUEST_API_DATA, getApiData)// REDUX STOREimport createStore, applyMiddleware, combineReducer from'redux'importcreateSagaMiddlewarefrom'redux-saga'import all from'redux-saga/effects'importloggerfrom'redux-logger'importuserReducerfrom'./reducers/user'importuserSagafrom'./sagas/user'function*saga()yieldall([userSaga()])exportconststore=()=>const sagaMiddleware =createSagaMiddleware()const store =createStore(combineReducer(users: userReducer),applyMiddleware(sagaMiddleware, logger)) 
 sagaMiddleware.run(saga)return store;// USER COMPONENTimportReactfrom'react'import connect from'react-redux'import requestApiData from'./actions'classUserextendsReact.ComponentcomponentDidMount()this.props.fetchAll()render()const users =this.props.stateconst results = users.length>0? users :[]return(<div>results.map((v)=>(<ul key=v.id><li>v.username</li></ul>))</div>)constmapStateToProps=(state)=>( state )constmapDispatchToProps=(dispatch)=>(fetchAll:()=>dispatch(requestApiData()))exportdefaultconnect(mapStateToProps, mapDispatchToProps)(User)

Te mostramos reseñas y valoraciones

Si te ha sido de ayuda nuestro artículo, sería de mucha ayuda si lo compartieras con otros desarrolladores y nos ayudes a difundir esta información.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada.