no data in next-redux-wrapper

I've been struggling to get my Next.js app working with getServerSideProps() for server-side rendering. I attempted to use next-redux-wrapper but the state is coming back empty.

*Note: Redux was functioning properly while on the client side, but now I'm trying to retrieve the state in getServerSideProps() and pass it into the component so it can be rendered on the server.

https://i.sstatic.net/58Q5S.png

store.js:

const reducer = combineReducers({
    productList: productListReducer,
    categoryList: categoryListReducer,
})

const middleware = [thunk]

const makeStore = context => createStore(reducer, composeWithDevTools(applyMiddleware(...middleware)))

const wrapper = createWrapper(makeStore, {debug: true})

export default wrapper

reducer.js:

export const productListReducer = (state = { products: [] }, action) => {
    switch (action.type) {
        case HYDRATE:
            return {...state, ...action.payload}
        case 'PRODUCT_LIST_REQUEST':
            return { loading: true, products: [] }
        case 'PRODUCT_LIST_SUCCESS':
            return { loading: false, products: action.payload }
        case 'PRODUCT_LIST_FAIL':
            return { loading: false, error: action.payload }
        default:
            return state
    }
}

_app.js:

import wrapper from '../redux/store'

function MyApp({ Component, pageProps }) {
  return (
    <Component {...pageProps} />
  )
}

export default wrapper.withRedux(MyApp)

index.js:

import wrapper from '../redux/store'

export const getServerSideProps = wrapper.getServerSideProps(store => ({req, res}) => {
  const state = store.getState()
  const { products } = state.productList

  return {props: {products: products}}
})


export default function Home({products}) {

  return (
    <>
      <div>{products}</div>
    </>
  )
}

Answer №1

page.js:

const mapDispatchToProps = (dispatch) => {
return {
  getProducts: bindActionCreators(getProducts, dispatch),
  getCategories: bindActionCreators(getCategories, dispatch)
}

}

function mapState(state) {
    return {
        productsList: state.productList.products,
        isLoading: state.productList.loading,
        categoriesList: state.categoryList.categories,
        isCategoryLoading: state.categoryList.loading
    }
}

CategoryPage.getInitialProps = wrapper.getInitialPageProps((store) => async () => {
    await store.dispatch(getProducts())
    await store.dispatch(getCategories())
})
  
export default connect(mapState, mapDispatchToProps)(CategoryPage)

reducer.js:

import { HYDRATE } from "next-redux-wrapper"

export const categoryReducer = (state = { categories: [] }, action) => {
    switch (action.type) {
        case HYDRATE:
            return {...state, ...action.payload}
        case 'CATEGORY_REQUEST':
            return { loading: true, categories: [] }
        case 'CATEGORY_SUCCESS':
            return { loading: false, categories: action.payload }
        case 'CATEGORY_FAIL':
            return { loading: false, error: action.payload }
        default:
            return state
    }
}

store.js:

const allReducers = combineReducers({
productList: productListReducer,
categoryList: categoryReducer
})

const rootReducer = (state, action) => {
    if (action.type === HYDRATE) {
      const updatedState = {
        ...state,
        ...action.payload
      }
      return updatedState
    } else {
      return allReducers(state, action)
    }
}
const applyMiddleWare = (middleware) => {
  if (process.env.NODE_ENV !== 'production') {
    const { composeWithDevTools } = require('redux-devtools-extension')
    return composeWithDevTools(applyMiddleware(...middleware))
  }
  return applyMiddleware(...middleware)
}

export const createMyStore = (context) => {
  const newStore = createStore(rootReducer, applyMiddleWare([thunk]))
  return newStore
}

export const myWrapper = createWrapper(createMyStore, { debug: true })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building Dynamic Props in Vue.js using v-select Component

I am utilizing a chart that relies on properties for data. <template> <v-row> <v-col col="12" sm="12"> <Chart :data="series2"></Chart> ### This chart receives the props < ...

three.js: Converting 2 directional vectors into either 3 rotations or a matrix

My coding system consists of 2 unit vectors labeled 'Ox' and 'Oy', 1 insertion point, and nearby is an 'Oz' vector that always appears to be {0 0 1}. For instance (after 2 rotations): Ox:{x: 0.956304755963036, y: -0.29237170 ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

An issue has been encountered in NodeJS with a route that begins with a percent sign causing an error

I have a NodeJS server set up with the following backend configuration: app.use(express.static(__dirname)) app.get('/', function(req, res){ res.send('main page here') }); app.get('/*', function(req, res){ res.send(&apos ...

The positioning of drawings on canvas is not centered

I'm facing an issue while attempting to center a bar within a canvas. Despite expecting it to be perfectly centered horizontally, it seems to be slightly off to the left. What could possibly be causing this discrepancy? CSS: #my-canvas { border: ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

Locating the chosen value from a dropdown within a div: A step-by-step

Code Viewer: <div id="maindiv"> for(i=1;i<3;i++) { <div id="subdiv"> @html.dropdownlistfor(m=>m.id,new selectlist((viewbag.country) as selectlist,"Value","Text"),new{@class="country"}) ...

Develop a technique to transfer properties to elements in a REACT environment

Is there a way to create a function that passes props to multiple components? passingPropsMethod(){ return( something={this.state.something} something2={this.state.something2} ) } I attempted this code, but it showed "Unreachable co ...

Showing child elements within a div using AngularJS

I am eager to create a straightforward AngularJS website that will showcase an initially hidden HTML element along with all of its children. Below is the HTML structure snippet I plan to use: <div class="hiddenStuff"> <h3>Game Over</h3&g ...

Determine the availability of a distant website through AJAX requests

My website runs PHP's cURL to check the online status of 5 different URLs, however, this process tends to slow down the page load time significantly, especially if one of the sites being checked is not working. Someone suggested using jQuery's a ...

Tips for invoking a reduce mechanism within a separate function

I need assistance with implementing a reduce function: users.reduce(function (acc, obj) { return acc + obj.age/3; }, 0); within the following function structure: function calculateUserAverageAge(users) {}; To analyze this array of objects and calculate ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

The use of backticks within an HTML document for nesting purposes is not permitted

Currently, I am utilizing nodemailer to send HTML template code in Node.js. However, the issue I am encountering is that I cannot nest backticks within it: Here's my code snippet: let mailDetails={ from: 'example@example.com', to: & ...

Troubleshooting WebSocket issues while utilizing Apollo Server with subscriptions within next.js API routes

Currently, I am in the process of setting up GraphQL Subscriptions within a next.js 9.x application. This app is purely for experimentation purposes to test Apollo Server subscriptions. Instead of a real database, I am using an array where new users are ad ...

When using the "Content-Disposition" header with the value "inline;filename=" + fileName, it does not necessarily guarantee that PDF files will be displayed directly

When a link is clicked, I want the PDF file to first show in a new tab as a preview before allowing users to download it. I researched and found advice suggesting that including these two headers would achieve this: Response.AddHeader("Content-Dispositio ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

Vue dynamic components fail to re-render within a v-for loop upon data changes

I've created a dynamic table component that allows me to modify columns by changing their ordering, adding new ones, or removing existing ones. The structure of my table body is as follows: <tr v-for="row in data" :key="row.id"& ...

Eliminating repeating entries in autocomplete results JSON

I am facing a challenge where I have integrated two feature classes, resulting in occasional duplication of results in the autosuggest feature. I am exploring options to detect and display alternatives instead of repeating the same result twice. Check out ...

Encountering an error when attempting to upload a file to S3 using JS Vue

I'm attempting to upload a file to my S3 bucket using the aws-s3 library, but I am encountering this error in the console: https://i.stack.imgur.com/lk47U.png Here is the code for the component: <template> <input type="file" @ch ...

Automatically divide the interface into essential components and additional features

Consider the following interfaces: interface ButtonProps { text: string; } interface DescriptiveButtonProps extends ButtonProps { visible: boolean, description: string; } Now, let's say we want to render a DescriptiveButton that utilize ...