I have an issue with my redux. This is the first time I am using it in React. I have managed to successfully use it for logging and registering users. However, I have an array of objects created on backend which I am fetching with axios. Axios logs the data and my action creator also logs data in payload. However, it does not update my new state. I have no idea what I'm doing wrong as I tried it exactly the same way as with my login and register states, however these were only boolean values. I have googled and searched for a solution. I tried mapping new array, Object.assign and many others but I can't seem to get it working. Is there any special way on creating new array in state? or can I just assign it action.payload? I appreciate all help
// store.js
import { applyMiddleware, createStore } from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import reducer from './reducers/reducer';
const middleware = applyMiddleware(logger, thunk);
export default createStore(reducer, middleware);
// rootReducer.js
import { combineReducers } from 'redux';
import registerReducer from './registerReducer';
import loginReducer from './loginReducer';
import productsReducer from './products';
export default combineReducers({
registerReducer,
loginReducer,
productsReducer
});
// productsReducer // I believe sth must be wrong here
import { SHOW_PRODUCTS, SELECT_PRODUCT } from '../actions/products';
const initialState = {
productsList: []
};
const productsReducer = (state = initialState, action) => {
switch (action.type) {
case SHOW_PRODUCTS:
return {...state, productsList: action.payload}
}
return state;
}
export default productsReducer;
// actions.js
import { SHOW_PRODUCTS, SELECT_PRODUCT } from './constants';
export function showProducts(products) {
return {
type: SHOW_PRODUCTS,
payload: products
};
}
// component.js
import React, { Component } from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import ProductsList from './ProductsList';
import { showProducts } from '../actions/products';
class Home extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.getProducts();
}
render() {
return(
<div>Home Page
<ProductsList />
</div>
)
}
}
const mapStateToProps = (state) => {
return {
productsList: state.productsReducer.productsList
};
}
const mapDispatchToProps = (dispatch) => {
return {
getProducts: () => {
axios.get('http://localhost:5000/product/list')
.then((res) => {
console.log(res.data);
dispatch(showProducts(res.data))
})
.catch(err => console.log(err))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
I am also including a link to an image with my redux logger.
https://i.sstatic.net/bTnYh.png
There's probably a very small, stupid mistake in here as I'm quite new to React and completely new to Redux
console.log()the action in theproductsReducer?