1

React hooks object update gets strange behaviour on Safari browser(only on Safari browser)

const [state, setState] = React.useState({
  show_welcome: true,
  show_inline: false,
  restriction: false,
  request_dp: false,
  prevent_rtl: false,
  lang: "ta"
});

setState

const handleToggle = ({ target }) => {
  setState(s => ({ ...s, [target.name]: !s[target.name] }));
};

Is there anything break the order of object for Safari browser

React hooks object update gets strange behaviour on Safari browser

Edit infallible-keldysh-uolgt

Mo.
  • 21,971
  • 31
  • 138
  • 201
  • 1
    Did you check the same logic without the CSS which comes from `react-bootstrap`? Why do you think its a "react-hooks" problem? – Dennis Vash Jan 07 '20 at 16:23
  • https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Dennis Vash Jan 07 '20 at 16:26
  • Have you tried adding a `key={key}` on the form inputs? – dashton Jan 07 '20 at 16:28
  • You are placing the updated property at the end of the object on each update. Hence the item that you interact with is being rendered at the bottom. – sdgluck Jan 07 '20 at 16:31

1 Answers1

1

The reason this is happening is because it's re-rendering the array that you are using for the keys and the keys aren't in the same order as they were in the first render. You can see this by adding a console.log(state) just before the first return. Safari is more strict in this than Chrome or Firefox.

You can fix this by sorting the array before using it to render.

You can also fix this by changing your toggle function to something like this:

const handleToggle = ({ target }) => {
    const tempState = { ...state };
    tempState[target.name] = !tempState[target.name];
    setState(tempState);
  };
technicallynick
  • 1,422
  • 5
  • 14