Home > Back-end >  React component not updating when redux state changes
React component not updating when redux state changes

Time:03-01

I have a React component that maps state to props to get data via redux. Everything works fine with the action and the value being updated properly in the reducer. My only problem is that when the state value changes, I want my component to re render so that it is always displaying the most up to date value in the reducer. As of right now I have to call a separate function that refreshes the component, but I'd rather have it automatically re render every time that value changes in the reducer.

Action:

export const createPickup = (selected, pickups) => dispatch => {
  let icon;
  icon = check(selected);
  pickups.icon = icon;
  return API('/createPickUp/', {
    ...pickups,
  })
    .then(res => {
      dispatch({type: types.CREATE_PICKUP, res});
    })
    .catch(err => console.log(err));
};

Reducer:

const initialState = {
  pick: [],
};
export default function pickup(state = initialState, action) {
  switch (action.type) {
    case types.GET_PICK:
      return {
        pick: action.pickup,
      };
    case types.CREATE_PICKUP:
      return {
        pick: [action.res, ...state.pick],
      };
    case types.DEL_GAME:
      return {
        pick: state.pick.filter(p => p._id !== action.id),
      };
    case types.START_GAME:
      return {
        pick: state.pick.map(p =>
          p._id === action.id ? {...p, start: true} : p,
        ),
      };
    case types.STOP_GAME:
      return {
        pick: state.pick.map(p =>
          p._id === action.id ? {...p, stop: true} : p,
        ),
      };
    default:
      return state;
  }
}

CodePudding user response:

Use useSelector hook in Functional Component as it automatically subscribes to the state and your component will re-render. If you are using Class Component then use connect() from redux and mapStateinProps.

CodePudding user response:

I am assuming you have passed the reducer to the global Store. Now... make sure you have the up to date value in your component.. try consoling it like this...

import {useSelector} from 'react-redux';
const YourCmponent = () => {
 
 const reduxState = useSelector(state => state);
 console.log(reduxState); 

 return <div>Your Content</div>

}

That way you can get access to the redux store. And you don't need to make any other function for updating component You will always get updated value here.

  • Related