Search code examples
reactjsreduxredux-thunk

Why is my redux state not updating after dispatch


I am using react with redux-thunk and when I dispatch action to call an api I can see the data updating in redux dev tools but it's not been rendered on the component.

My action:

 export const fetchPosts = () => async(dispatch) => {
try {
    const {data} = await API.fetchPosts();
    dispatch({
        type: "FETCH_POSTS",
        payload: {
            posts: data.posts
        },
      });

  } catch (error) {
    console.log(error)
  }
  }

Reducer:

const postsReducers = (state = [], action) => {
switch (action.type) {
case "FETCH_POSTS":
    state.push(...action.payload.posts);
  return state;

default:
  return state;
 }
};

export default postsReducers;

Component:

const Home = () => {
const dispatch = useDispatch();
const posts = useSelector(state => state.posts);

useEffect(() => {
  if(!posts.length){
    dispatch(fetchPosts())
     console.log(posts.length) //returns 0
  }
}, [dispatch, posts]);

....
}

What could I be missing?


Solution

  • Unless you are using the new redux toolkit, redux requires you to not mutate state.

    Instead of pushing to state and returning a mutated state, try creating a new array using spread operator like so:

    return [...state, ...action.payload.posts];