0
votes

I have a simple reducer that just define a default variable 'theme' and do nothing but return this value:

appreducer.js

const initialState = {
  theme: 'skyhola',
};

export default (state = initialState, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

On the components that are not the main App.js, I can read this state:

import  React, { Component } from 'react';
import { connect } from 'react-redux';
class TestColors extends Component {
  render() {
    return (
      <div>
         Theme: { this.props.theme }  // <---it's ok, print 'sky'
      </div>
    );
  }
}

export default connect(
  (state) => ({ theme: state.app.theme }),
)(TestColors );

But how to read it on the main component? because i need to write in the render in:

<ThemeProvider theme={ HERE MY STATE THEME !! }>

the state are in process of creation and console.log in render, or ComponentDidMount give me empty {}, i can't wray App with 'connect' from redux, because it's the app is being created...

app.js

const store = createStore(
  combineReducers({
    apollo: client.reducer(),
    app: appReducer,
  }),
  {},
  compose(
    applyMiddleware(client.middleware()),
    // If you are using the devToolsExtension, you can add it here also
    window.devToolsExtension ? window.devToolsExtension() : f => f,
  ),
);

class App extends Component {

  componentDidMount () {
    console.log(this.props);  <--- nothing here, how to read the state?
  }
  render() {

    return (
      <ApolloProvider store={store} client={client}>
        <BrowserRouter>
          <ThemeProvider theme={ HERE MY STATE THEME !! }>

              <Switch>
                <Route exact path="/signin" component={SignInPage} />
              </Switch>


          </ThemeProvider>
        </BrowserRouter>
      </ApolloProvider>
    );
  }
}

export default App;
2

2 Answers

1
votes

To read the state in this case you need to call the getState method of the store.

class App extends Component {
  componentDidMount () {
  console.log(store.getState()); // current state of the application
  // Prints: app: {theme: "skyhola"}
}

You can check this fiddle.

0
votes

you mapStateToProps should be state.theme instead of state.app.theme.

export default connect(
  (state) => ({ theme: state.theme }),
)(TestColors );

You need to call the constructor of the App component.

class App extends Component {
  constructor(props){
    super(props)
  }
  ...
}