1

There is a challenge update existing elements value in json array in redux store by an action creater. You can run code here also shared it below;

console.clear()
const CreateTeam = (team, point) => {
  return {
    type:"CREATE_TEAM",
    payload: {team, point}
  }
}

const UpdateTeam = (team, point) => {
  return {
    type:"UPDATE_TEAM_POINT",
    payload: {team, point}
  }
}

const TeamReducer = (state = [], action) => {
  if(action.type == "CREATE_TEAM")
     {
      return [...state, action.payload]
     }
    if(action.type == "UPDATE_TEAM_POINT")
     {
       let point=action.payload.point;

      return [...state, {
        ...state.teams,
        point:point
      }]
     }
  return state;
}

const { createStore, combineReducers } = Redux;

const league = combineReducers({
  teams: TeamReducer
})

const store = createStore(league);

store.dispatch(CreateTeam("TeamA",10));
store.dispatch(CreateTeam("TeamB",20));

store.dispatch(UpdateTeam("TeamA",15));//not work
console.log(store.getState())

create actions works fine, I expected the point value of TeamA set to 15.. but its added new object has only "point" property value 15

1 Answer 1

2

There is an error in name of actionTypes:

  1. action dispatches type:"UPDATE_TEAM"
  2. reducer handles action.type == "UPDATE_TEAM_POINT"

You have to perform immutable change, try this:

const TeamReducer = (state = [], action) => {
  if(action.type == "CREATE_TEAM")
     {
      return [...state, action.payload]
     }
    if(action.type == "UPDATE_TEAM")
     {
       const {team, point} = action.payload;
       const changedIdx = state.findIndex((item) => item.team === team);
       return [...state.slice(0, changedIdx), action.payload, ...state.slice(changedIdx + 1)]

     }
  return state;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I also updated my answer, you were not updating your state correctly, there was nothing like teams in your state.
works nice, but I wonder Does this way of updating store triggers the react component which use that list as props?
You shold somehow connect react and redux worlds. The best way is the react-redux library. See this section in redxu documentation: redux.js.org/basics/usage-with-react#installing-react-redux

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.