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

220
Views
¿Cómo enviar una acción desde dentro de getInitialProps?

Estoy tratando de implementar Redux en una aplicación Next.js y tengo problemas para que la función de despacho funcione en getInitialProps . La tienda se devuelve como indefinida por alguna razón que no puedo entender. Estoy usando next-redux-wrapper. He seguido la documentación en la página de GitHub de next-redux-wrapper pero en algún lugar del camino sale mal. Sé que el código funciona: utilicé artPieces para buscar directamente las piezas de arte y luego funcionó bien, pero quiero usar Redux en su lugar. Estoy cambiando una aplicación react/express.js a una aplicación Next.js donde usaré la API para las operaciones básicas del servidor necesarias. Esta es solo una pequeña aplicación de blog.

Aquí está mi store.js :

 import { createStore } from 'redux'; import { createWrapper, HYDRATE } from 'next-redux-wrapper'; // create your reducer const reducer = (state = { tick: 'init' }, action) => { switch (action.type) { case HYDRATE: return { ...state, ...action.payload }; case 'TICK': return { ...state, tick: action.payload }; default: return state; } }; // create a makeStore function const makeStore = (context) => createStore(reducer); // export an assembled wrapper export const wrapper = createWrapper(makeStore, { debug: true });

Y aquí está el _app.js :

 import './styles/globals.css'; import { wrapper } from '../store'; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default wrapper.withRedux(MyApp);

Y finalmente aquí es donde no funciona. Intentando llamar al envío en el contexto a un subcomponente a _app.js :

 import React from 'react'; import { ArtPiecesContainer } from './../components/ArtPiecesContainer'; import { useDispatch } from 'react-redux'; import axios from 'axios'; import { getArtPieces } from '../reducers'; const Art = ({ data, error }) => { return ( <> <ArtPiecesContainer artPieces={data} /> </> ); }; export default Art; Art.getInitialProps = async ({ ctx }) => { await ctx.dispatch(getArtPieces()); console.log('DATA FROM GETARTPIECES', data); return { data: ctx.getState() }; };
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Esto probablemente debería funcionar con "next-redux-wrapper": "^7.0.5"

_app.js

 import { wrapper } from '../store' import React from 'react'; import App from 'next/app'; class MyApp extends App { static getInitialProps = wrapper.getInitialAppProps(store => async ({Component, ctx}) => { return { pageProps: { // Call page-level getInitialProps // DON'T FORGET TO PROVIDE STORE TO PAGE ...(Component.getInitialProps ? await Component.getInitialProps({...ctx, store}) : {}), // Some custom thing for all pages pathname: ctx.pathname, }, }; }); render() { const {Component, pageProps} = this.props; return ( <Component {...pageProps} /> ); } } export default wrapper.withRedux(MyApp);

e Index.js

 import { useEffect } from 'react' import { useDispatch } from 'react-redux' import { END } from 'redux-saga' import { wrapper } from '../store' import { loadData, startClock, tickClock } from '../actions' import Page from '../components/page' const Index = () => { const dispatch = useDispatch() useEffect(() => { dispatch(startClock()) }, [dispatch]) return <Page title="Index Page" linkTo="/other" NavigateTo="Other Page" /> } Index.getInitialProps = wrapper.getInitialPageProps(store => async (props) => { store.dispatch(tickClock(false)) if (!store.getState().placeholderData) { store.dispatch(loadData()) store.dispatch(END) } await store.sagaTask.toPromise() }); export default Index

Para el resto del código, puede consultar nextjs/examples/with-redux-saga, pero ahora que estoy publicando esta respuesta, están usando la versión anterior en next-redux-wrapper (versión 6).

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!