I saw similar problems on Stackoverflow but the problem was that they mutate the state and that doesn’t let react-redux update the view I don’t know if I have the same problem but I used this code structure in previous project and it worked fine please help .
the reducer code
I use the same structure in similar apps and it works . in the redux
devtools
the store gets updated already but that didn’t change the React view
.
import * as actionTypes from '../actions/constants';
export default (state = [], action) => {
switch (action.type) {
case actionTypes.LOAD_ALL_POSTS:
return [...state, ...action.allPosts];
case actionTypes.ADD_POST:
return [...state, action.post];
case actionTypes.EDIT_POST:
return state.map(post => {
if (post.id === action.id) {
return {
...post,
...action.updates,
};
}
return post;
});
case actionTypes.DELETE_POST:
return state.filter(({ id }) => id !== action.id);
default:
return state;
}
};
Here are my actions and I use react-redux
to connect redux
with react the redux
is connected with react successfully and the LOAD_ALL_POSTS action is working correctly but when I try to use ADD_POST
action it only updates the store
and didn’t update the view.
import uid from 'uuid';
import * as actionTypes from './constants';
export const loadAllPosts = (allPosts = []) => ({
type: actionTypes.LOAD_ALL_POSTS,
allPosts,
});
export const loadLatestPosts = num => ({
type: actionTypes.LOAD_FEATURED_POSTS,
number: num,
});
export const addPost = post => ({
type: actionTypes.ADD_POST,
post: { ...post, id: uid() },
});
export const editPost = (id, updates = {}) => ({
type: actionTypes.EDIT_POST,
id,
updates,
});
export const deletePost = id => ({ type: actionTypes.DELETE_POST, id });
//connect Redux with React
const mapStateToProps = state => ({
posts: state.posts,
});
export default connect(mapStateToProps, { filterByType })(Projects);
The reducer state is an array of objects I use array.map
to loop through its items and render them in React Component.
Store
this is configurStore();
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import posts from '../reducers/posts';
import filters from '../reducers/filters';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default () => {
const store = createStore(
combineReducers({
posts,
filters,
}),
composeEnhancers(applyMiddleware(thunk))
);
return store;
};