1

Estoy estudiando redux-saga y quiero hacer fetch a esta direccion:

https://jsonplaceholder.typicode.com/posts

y en mi carpeta redux tengo lo siguiente:

(se puede chequear esta informacion en el repositorio https://github.com/jotasenator/redux-saga-fetching-example/tree/main/src)

\src\redux\api.js

import axios from 'axios'

export const loadPostApi = async () => {
    await axios.get(`https://jsonplaceholder.typicode.com/posts`)
}

el get request a la direcion en question

src\redux\app.actions.js

export const loadPostStart = () => ({
    type: 'LOAD_POST_START',

})
export const loadPostSuccess = (posts) => ({
    type: 'LOAD_POST_SUCCESS',
    payload: posts,
})
export const loadPostFail = (error) => ({
    type: 'LOAD_POST_FAIL',
    payload: error,
})

estas son las funciones las acciones

src\redux\app.reducer.js

const INITIAL_STATE = {
    loading: false,
    posts: [],
    errors: null,
}

export const appReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case 'LOAD_POST_START':
            return {
                ...state,
                loading: true,
            }
        case 'LOAD_POST_SUCCESS':
            return {
                ...state,
                posts: action.payload,
                loading: false,
            }
        case 'LOAD_POST_FAIL':
            return {
                ...state,
                errors: action.payload,
                loading: false,
            }

        default:
            return state;
    }
}

el reducer del fetching, actualizando el estado

src\redux\counterReducer.js

import { types } from "./types";

const initialState = {
    value: 0
}

export const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case types.adicionar:
            return {
                ...state,
                value: state.value + 1
            }

        case types.resetear:
            return {
                ...state,
                value: 0
            }

        case types.restar:
            return {
                ...state,
                value: state.value - 1
            }

        default:
            return state
    }
}

este es el reducer del counter app, con diferente enfoque, los types estan aislado en otro file

src\redux\rootReducer.js

import { combineReducers } from 'redux'
import { counterReducer } from './counterReducer'
import { appReducer } from './app.reducer'

export const rootReducer = combineReducers({
    counterReducer,
    appReducer
})

el rootReducer para unir los reducers


src\redux\sagas.js

import { put, takeLatest, call } from 'redux-saga/effects'
import { loadPostApi } from './api'
import { loadPostFail, loadPostSuccess } from './app.actions'

export function* onLoadPostStartAsync() {
    try {
        const response = yield call(loadPostApi)
        yield put(loadPostSuccess(response.data))
    } catch (error) {
        yield put(loadPostFail(error))

    }
}

export function* onLoadPost() {
    yield takeLatest('LOAD_POST_START', onLoadPostStartAsync)

}

export default function* rootSaga() {
    yield ([
        onLoadPost(),
    ])
}

saga onLoadPostStartAsync llamado por saga onLoadPost dentro de rootSaga

src\redux\store.js

import { applyMiddleware, compose, createStore } from "redux";
import createSagaMiddleware from 'redux-saga'

import { rootReducer } from "./rootReducer";

import rootSaga from "./sagas";

const sagaMiddleware = createSagaMiddleware()

const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose

const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))

export const store = createStore(rootReducer, enhancer)

sagaMiddleware.run(rootSaga)

este es el store con el redux-devtool_extension,the rootReducer, y corriendo rootSaga

src\redux\types.js

export const types = {
    adicionar: 'ADICIONAR',
    resetear: 'RESETEAR',
    restar: 'RESTAR'
}

estos son los types del reducer del counterApp

src\Counter.js

import React from 'react'
import { useDispatch, useSelector } from 'react-redux'

export const Counter = () => {

  const dispatch = useDispatch()
  const { value } = useSelector(state => state.counterReducer)

  const handleAdicionar = () => {
    dispatch({ type: 'ADICIONAR' })
  }
  const handleResetear = () => {
    (value !== 0) && dispatch({ type: 'RESETEAR' })
  }
  const handleRestar = () => {
    dispatch({ type: 'RESTAR' })
  }
  console.log(value)
  return (
    <div>
      <button onClick={handleAdicionar}>Adicionar</button>
      {' '}
      <button onClick={handleResetear}>Resetear</button>
      {' '}
      <button onClick={handleRestar}>Restar</button>
      <hr />

    </div>
  )
}

el componente Counter funciona correctamente

src\Fetching.js

import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { loadPostStart } from './redux/app.actions'


export const Fetching = () => {
    const dispatch = useDispatch()

    const fetchPost = () => {
        dispatch(loadPostStart())
    }

    const state = useSelector(state => state.appReducer)
    console.log(state)


    return (
        <>
            <h1>Fetching from https://jsonplaceholder.typicode.com</h1>
            <button onClick={fetchPost}>Fetching</button>
            {
                !state.loading && state.posts.map((post) => (
                    <li key={post.id}><h2>{post.title}</h2></li>

                ))
            }

        </>
    )
}

el componente Fetching, cuando se le da click al button llama a fetchPost que hace dispatch loadPostStart() que es lo mismo que dispatch {type: 'LOAD_POST_START'}, peor no ocurre nada cuando doy click, no obtengo informacion de https://jsonplaceholder.typicode.com/posts


src\index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { store } from './redux/store';
import { Provider } from "react-redux";
import { Unificator } from './Unificator';

ReactDOM.render(
  <Provider store={store}>
    <Unificator />
  </Provider>,


  document.getElementById('root')
);

componente Unificator tiene al componente Counter y Fetching

src\Unificator.js

import React from 'react' import { Counter } from './Counter' import { Fetching } from './Fetching'

export const Unificator = () => { return (

    </div>
)

}

como pueden ver se trata sobre dos casos, uno es el famoso Counter, que funciona correctamente, pero el otro no funciona adecuadamente, asi que cuando trato de hacer fetching no logra obtener informacion alguna

obviamente estoy haciendo algo incorrecto por favor ayuda

gracias de antemano

1
  • Pusiste algun console.log en el fetch para al menos saber si hace o no la llamada? el 10 jul. 2021 a las 15:08

0

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

Examina otras preguntas con la etiqueta o formula tu propia pregunta.