Answers for "redux with react reducer"

14

reducer in react example

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
Posted by: Guest on June-21-2020
1

Update State in react redux reducer

case foodConstants.FOOD_SUCCESS_POST: {

  let updatedItems = { ...state.items };
  const itemIndex = updatedItems.findIndex((food1) => food1.id === action.id);

  if(itemIndex > -1){
    updatedItems[itemIndex] = {
        ...updatedItems[itemIndex],
        ...action,
    }
  }

 return { ...state, items: updatedItems };
}
Posted by: Guest on June-26-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language