Redux store get empty in component

3.5k Views Asked by At

I have a problem with getting the redux store in my component. I am using redux-react async to fetch data from api. I got the data from jsonplaceholder api, however I have a problem configuring the store and connecting the store with the root component. I can see there is data in the store using a logger and the redux developments tools extension.

I did console.log(store.getState()) in the index component and the store is empty: clientData: {}. I have no idea what I have missed, I need some tips.

//action creator

export const datafeachsuccess = data => {
    return {
      type: FEACH_SUCCESS,
      data: data
    };
  } 

export const getClientData = () => {
    return (dispatch) => {
        return fetch('https://jsonplaceholder.typicode.com/posts')
            .then(res => {
                return res.json();
            }).then(json => {
                dispatch(datafeachsuccess(json))
            })
          }}

// client data reducer

const clientReducer =(state = {}, action)=>{
    switch (action.type) {
      case FEACH_DATA:
        return {
          ...state,
          requestData: 'requesting Data'
        };
      case FEACH_SUCCESS:
        return {
          ...state,
          client: action.data
        };
      case FEACH_FAILD:
        return {
          ...state,
          error: action.data
        }
      default:
        return state;
    }
  }
export default  clientReducer; 

//rootreducer

import { combineReducers } from 'redux';
import clientReducer from './clientreducer/clientreducer'

const rootReducer = combineReducers({
    clienetData: clientReducer
})

export default rootReducer; 

//configuring store

import { createStore, applyMiddleware } from 'redux';
import rootReducer from './../reducer/rootReducer'
import thunkMiddelware from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import { createLogger } from 'redux-logger'

const loggerMiddleware = createLogger()

export default function configureStore() {
   return createStore(
    rootReducer,
    composeWithDevTools(
      applyMiddleware(thunkMiddelware, loggerMiddleware)
    )
  );
} 

//index component

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import createHistory from 'history/createBrowserHistory'
import { Provider } from 'react-redux';
import {Router} from 'react-router-dom';
import configureStore from './redux/store/configureStore'


const history = createHistory(); 
const store = configureStore(); 
console.log(store.getState())

const app =(
    <Provider store={store}> 
        <Router history={history}>
            <App/>
        </Router>
    </Provider>
)

ReactDOM.render(app, document.getElementById('root'));
registerServiceWorker();

//connecting with component

import React, { Component } from 'react';
import Grid from '@material-ui/core/Grid';
import {Link} from 'react-router-dom'
import { connect } from 'react-redux';
import { withRouter } from 'react-router'
import {getClientData} from './../../redux/actions/feachclientData/requestData'
import './css/user.css'


class UserInfo extends Component {
  constructor(props){
    super(props)
    this.state = {
    }
  }

  componentDidMount(){
    this.props.getClientData(); 

  }
  render() {
    if(this.props.userData === 0) return null; 
    return (
      <Grid container space={8} justify='center'> 

      </Grid> 
    );
  }
}

const mapStateToProps = state => {
  return {
   userData: state.clientData|| []
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getClientData: () => dispatch(getClientData())
  };
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(UserInfo))

enter image description here

2

There are 2 best solutions below

0
On

You are calling

console.log(store.getState())

Before you fetch the data from the server.
Try to call getClientData first, then on the callback log store.getState()

1
On

When you call console.log(store.getState()) you have not called the api yet, so there is no posts. You seem to call the api only once the UserInfo component is mounted (i.e. added to the DOM of the page)