score:1

Accepted answer

it's because you don't store the array in state. if you use usestate for array too, it will work correctly:

const {usestate} = react;

function blockeditor() {
  let [block1content, setblock1content] = usestate('1');
  let [block2content, setblock2content] = usestate('2');

  let [block1order, setblock1order] = usestate(0);
  let [block2order, setblock2order] = usestate(1);

  let [array, setarray] = usestate([block1content, block2content]);

  function blockswap() {
    const copy = [...array];
    [copy[0], copy[1]] = [copy[1], copy[0]];
    setarray(copy);
    setblock1order(copy.indexof(block1content));
    setblock2order(copy.indexof(block2content));
  }

  function log() {
    console.log('array: ', array);
    console.log('blockorder: ', block1order, block2order);
  }
  
  return (
    <div>
      <button onclick={blockswap}>swap blocks</button>
      <button onclick={log}>console log results</button>
    </div>
  );
}

reactdom.render(<blockeditor />, document.getelementbyid('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="react"></div>

it would also work without creating a copy of the array:

  function blockswap() {
    [array[0], array[1]] = [array[1], array[0]];
    setarray(array);
    setblock1order(array.indexof(block1content));
    setblock2order(array.indexof(block2content));
  }

Related Query

More Query from same tag