0

This is my state object. I am trying to change "isVisible" value from "HideUser" case that i provided below. But output is allways gives me same isVisible value. And i cant flip it. I would appreciate for any help. Note: when i say isVisible=false, it works. And isVisible value is allways same when i print.

state={
        users:[
          {
            id:1,
            isim:"Muhammedcan Pirinççi",
            okul:"Marmara",
            maaş:"a4000",
            isVisible:true
          },
          {
            id:2,
            isim:"Suat Pirinççi",
            okul:"Marmara",
            maaş:"a10000",
            isVisible:true
          }
        ],
        dispatch: action => {
          this.setState(state=>reducer(state,action))
        }
      }

HideUser case:

 case "HIDE_USER":
     
      return{
        ...state,
        users: state.users.map(user =>  {
          
          if (user.id===action.payload) {
            
        
            
            user.isVisible=!user.isVisible  
          
            return user
           
          }
          else{
            
            return user
          }
        })
        
      }
Canovich
  • 27
  • 6
  • 1
    You're mutating the state; do `return {...user, isVisible: !user.isVisible };` instead (this will create a copy and thus a new object, a change React can detect) –  Jul 27 '21 at 18:30
  • @ChrisG Thank you so much sir.. I dont know what to say.. Which topic is this? Where should i study this? – Canovich Jul 27 '21 at 18:33
  • The key is to understand that the `user` param passed to the map() function is a reference to the existing user object, but when you set state, you need to pass new copies of everything that changes. Check the `updating nested state object` section of this answer: https://stackoverflow.com/a/43639228/5734311 –  Jul 27 '21 at 18:46
  • @ChrisG Okay sir thank you so much. – Canovich Jul 27 '21 at 18:53
  • @ChrisG By the way i have another quick question if you have time. I am trying to understand dispatch, reducer and action in react (ContextApi). But my question is: While we can change anything in child components from parent components, why do we need to use "setState" inside of components? I mean if i wanna change something in component, if i can change it from parent,(which i can with dispatch,reducer and action), i wouldnt use SetState function inside of Component. If you can help me, i would be so happy. Thanks! – Canovich Jul 27 '21 at 18:55
  • I don't really use Redux, so not my area of expertise. However not every component needs its own state. You can have one that has just props (or neither). It depends on what it does. –  Jul 27 '21 at 19:52

0 Answers0