Reputation: 127
Reducer
const initialState = {
isLoadingDept:true,
isLoadingEmpDesig:true,
isLoadingEmpStatus:true,
isLoadingGroup:true
};
const isLoadingReducer = (state=initialState, action:any) =>{
switch (action.type) {
case "ISLOADING_Dept":
console.log(action.payload)
return {
isLoadingDept:action.payload
};
case "ISLOADING_EmpDesig":
return {
isloadingEmpDesig:action.payload
};
case "ISLOADING_EmpStatus":
return {
isLoadingEmpStatus:action.payload
};
case "ISLOADING_Group":
return{
isLoadingGroup:action.payload
};
default:
return state;
}
};
export default isLoadingReducer
Store
import {createStore} from 'redux'
import {combineReducers} from 'redux'
import isLoadingReducer from './reducers/isLoadingReducer'
const allReducers = combineReducers({
isLoading: isLoadingReducer
})
export default createStore(allReducers)
Index
import { render } from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import store from './redux/store'
import {Provider} from 'react-redux'
render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
Emp- file I want to use store in
function mapStateToProps(state:any){
return {
isLoadingDept: state.isLoading.isLoadingDept,
isLoadingEmpDesig: state.isLoading.isLoadingEmpDesig,
isLoadingEmpStatus: state.isLoading.isLoadingEmpStatus,
isLoadingGroup: state.isLoading.isLoadingGroup
}
}
class EmpList extends Component<any, any> {
//State and stuff
componentDidMount(){
console.log(this.props.isLoadingDept)
}
//stuff
}
export {EmpList as UnconnectedEmpList};
export default connect(mapStateToProps, {forwardRef:true})(EmpList)
console log in the last file logs undefined. I did this console log because nothing was working as it should, so I wanted to see what's going on. As you can see, I also did console log in Reducer, and it returns a value it should, so that part is working properly.
Upvotes: 0
Views: 102
Reputation: 44078
Your reducers all set one value and since the return value does not reference the original state, throw the rest of the state away, so
{
isLoadingDept:true,
isLoadingEmpDesig:true,
isLoadingEmpStatus:true,
isLoadingGroup:true
};
will become
{
isLoadingDept:true,
};
To avoid that, do
return {
...state,
isLoadingDept:action.payload
};
Also, just to make you aware of it: this is a pretty old style of Redux and nowadays we recommend writing that very differently, using the official Redux Toolkit. If you are just learning Redux, you might be following a very outdated tutorial. Please read through the official "Essentials" tutorial in that case.
Upvotes: 2