Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

333
Views
Reaccionar error de despacho redux: error no definido

Estoy tratando de hacer una aplicación con redux state management y react . Necesito fetch de una API, y puse toda la lógica de la API en otro archivo, estoy tratando de poner los datos de la respuesta al state en redux . Lo he intentado: archivo de secuencia de comandos API:

 import store from "./store"; import foo from "./foo.js"; fetch("http://my_fantastic_api.com/fooBar/"); .then((response)=>{ if (reponse.status.OK){ //The error: store.dispatch({ type:"MODIFY_XYZ" }); } }).catch(error =>{ throw new error() })

Pero cuando probé este método me encontré con este error cuando se llama a la función de fetch presionando un botón y se produjo un error.

El mensaje de error:

 Unhandled Rejection (Error): When called with an action of type "MODIFY_XYZ", the slice reducer for key "FOO_BAR" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.

Estoy tratando de encontrar una solución a este error si alguien tiene alguna idea o sugerencia se los agradezco mucho.

Saludos cordiales Alvin.

EDITAR:

almacenar archivo:

 //Importing packages import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App.jsx"; import reportWebVitals from "./reportWebVitals"; import { Provider } from "react-redux"; import { createStore } from "redux"; import reducers from "./redux/reducers/index.js"; //Redux configuration export const store = createStore(reducers); //Render app ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById("root") );
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

¿Qué hay en tu tienda? Creo que deberías usar el gancho de envío para enviar una acción.

about 4 years ago · Juan Pablo Isaza Report

0

En realidad, no exportaste la tienda correctamente. Creo que necesita crear la tienda en un archivo separado y luego exportarlo.

La estructura del archivo debería ser así:

 -src --index.js --app.js --store ---index.js ---reducers ----index.js

Ahora en el archivo src/store/index.js se verá así:

 import { createStore, applyMiddleware } from "redux"; import thunkMiddleware from "redux-thunk"; import { composeWithDevTools } from "redux-devtools-extension"; import Reducers from "./reducers"; const middlewares = applyMiddleware(thunkMiddleware); const enhancers = [middlewares]; const composedEnhancers = composeWithDevTools(...enhancers); const store = createStore(Reducers, undefined, composedEnhancers); export default store;

Si desea agregar las dev tools middleware y redux-thunk .


En el archivo src/store/reducers/index.js , todos los reductores se vincularán con el módulo CombinedReducers.

 import { combineReducers } from "redux"; import BlogReducer from "./blogReducer"; import UserReducer from "./userReducer"; export default combineReducers({ blogStore: BlogReducer, userStore: UserReducer, });

Aquí BlogReducer y UserReducer se unen con combineReducers . Puedes añadir el tuyo aquí-


Ahora en su archivo src/index.js agregue así:

 //Importing packages import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App.jsx"; import reportWebVitals from "./reportWebVitals"; import { Provider } from "react-redux"; import store from "./store"; //Render app ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById("root") );

En src/app.js puede llamar a la API y enviarla a la tienda redux-

 import { useEffect } from "react"; import { useSelector, useDispatch } from "react-redux"; const App = () => { //Get dispatch from useDispatch hook const dispatch = useDispatch(); //Get store from useSelector hook const store = useSelector( store => store) const getApiResponse = () => { fetch("http://my_fantastic_api.com/fooBar/"); .then((response)=>{ if (reponse.status.OK){ //The error: dispatch({type:"MODIFY_XYZ"}); } }).catch(error =>{ throw new error() }) } useEffect( () => { getApiResponse() },[]) return ( <h1> Hello World! </h1> ) } export default App; ``
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!