Home > OS >  Component not updating when mapped state changes
Component not updating when mapped state changes

Time:03-31

The map of the state it not immediately updating on state change, only updating in dom after other actions.

State initally declared:

const [actions, setActions] = useState({});

Function used to add to state:

const addAction = function(action, value){
      let actionObject = actions;
      let array = [];
      array.push({action: action, value:value});
      actionObject[selected.id] = array;
      setActions(actionObject);
}

State output to dom in render:

{           
   actions[selected.id] ? (
         actions[selected.id].map((a,i) => 
         <Flex key={i}>
         <Text>{a.action}</Text>
         <TextBox value={a.value}></TextBox>
         </Flex>)
    ) : ('') 
}

I have a button that when I click will call the function addAction. It should add the 'action'. Actions state is an object that will have ids, these ids will then have the action along with its value ie

{
    id0567: [{
      action: 'click link', 
      value: 'example.com'
    }]
}

It all seems to be working fine, however when I click the button and call addAction, this is not then loaded in the dom (in the 'Flex' element) I have to click on other things and go back for it to load.

CodePudding user response:

The issue here is that state is being assigned to directly which goes against the react way of doing things.

When using useState() as below:

const [actions, setActions] = useState({});

Any time you want to update the object, you should first make a mutable copy (let actionObject = {...actions}), make your changes to the object, then use setState() to update the in-state version of the object.

let actionObject = {...actions};
let array = [];
array.push({action: action, value:value});
actionObject[selected.id] = array;
setActions(actionObject);
  • Related