Skip to content

Instantly share code, notes, and snippets.

@varjmes
Last active July 18, 2017 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varjmes/18ff06d74a2cc2523d401a4dc11e6508 to your computer and use it in GitHub Desktop.
Save varjmes/18ff06d74a2cc2523d401a4dc11e6508 to your computer and use it in GitHub Desktop.
import axios from 'axios'
import getHost from '../../lib/getHost'
export const REQUEST_CATEGORY = 'REQUEST_CATEGORY'
function requestCategory (categoryId) {
return {
type: REQUEST_CATEGORY,
categoryId
}
}
export const RECEIVE_CATEGORY = 'RECEIVE_CATEGORY'
function receiveCategory (categoryId, data) {
return {
type: RECEIVE_CATEGORY,
categoryId,
category: data
}
}
export function fetchCategory (categoryId) {
const baseUrl = `${getHost()}/api/categories/${categoryId}`
return function (dispatch) {
dispatch(requestCategory(categoryId))
return axios.get(baseUrl)
.then((category) => {
console.log(category.data)
dispatch(receiveCategory(categoryId, category.data))
})
.catch(err => console.log(err))
}
}
import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import withRedux from 'next-redux-wrapper'
import Page from '../components/page'
import Category from '../components/category'
import { initStore } from '../store/store'
import { fetchCategory } from '../store/actions/actions'
class CategoryPage extends Component {
static async getInitialProps ({ store, isServer, req }) {
const categoryId = req.params.id
store.dispatch(fetchCategory(categoryId))
.then(console.log(store.getState()))
// returns an object {id: 1, label: 'butts'}
}
render () {
console.log(this.props) // returns a dispatch function, an my next.js url object
console.log(this.state) // null
return (
<Page>
<h1>Check to see if we got the category!!</h1>
</Page>
)
}
}
export default withRedux(initStore)(CategoryPage)
import React from 'react'
import { connect } from 'react-redux'
import Head from './head'
import Header from './header'
export default connect(state => state)(({ children }) => {
return (
<div>
<Head />
<Header />
<main className='container'>
{ children }
</main>
<style jsx>{`
.container {
margin: 0 auto;
padding: 15px;
max-width: 800px;
font-size: 1.2em;
text-align: center;
}
`}</style>
</div>
)
})
import { REQUEST_CATEGORY, RECEIVE_CATEGORY } from '../actions/actions'
export default categoryReducer
function categoryReducer (
state = {
isFetching: false,
category: {}
},
action) {
switch (action.type) {
case REQUEST_CATEGORY:
return Object.assign({}, state, {
isFetching: true
})
case RECEIVE_CATEGORY:
return Object.assign({}, state, {
isFetching: false,
category: action.category
})
default:
return state
}
}
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'
import categoryReducer from './reducers/reducers'
const initialState = {
isFetching: false,
category: {}
}
export const initStore = (intialState) => {
return createStore(categoryReducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)))
}
@danreeves
Copy link

Think I've found the two issues.

  1. state is only available in connected components, not withRedux page components.
  2. getInitialProps is only run on the server for first load, and the state wasn't being hydrated.

changes:

store.js

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';

import categoryReducer from './reducer';

+ const defaultState = {
+     isFetching: false,
+     category: {},
+ };
+ 
+ let initialState =
+     typeof __NEXT_DATA__ !== 'undefined'
+         ? __NEXT_DATA__.props.initialState
+         : defaultState;

export const initStore = intialState => {
    return createStore(
        categoryReducer,
        initialState,
        composeWithDevTools(applyMiddleware(thunkMiddleware))
    );
};

page.js

import React from 'react';
import { connect } from 'react-redux';

+ export default connect(state => state)(({ category, children }) => {
+     console.log(category);
    return (
        <div>
            <main className="container">
                <h1>
+                    Category is: {category.label}
                </h1>
                {children}
            </main>
            <style jsx>{`
                .container {
                    margin: 0 auto;
                    padding: 15px;
                    max-width: 800px;
                    font-size: 1.2em;
                    text-align: center;
                }
            `}</style>
        </div>
    );
});

screen shot 2017-07-18 at 00 04 55

@varjmes
Copy link
Author

varjmes commented Jul 18, 2017

YOU ARE THE BEST. THANK YOU

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment