score:1

Accepted answer

it's because you're updating the state on every render again and again. if you just simply call setdata() inside the function, it will call this setter that invokes a re-render and triggers react to call your app function again.

if you want to have a default state, you can do it like below. if you want to update the state, it should be done by other actions, like the click of a button, fetching some data, etc.

check out the demo below where i added a button that adds a new name to your nodes array:

function app() {
  const [data, setdata] = react.usestate({
    nodes: [
      { name: 'max' },
      { name: 'george' },
      { name: 'jesus' },
      { name: 'ben' },
      { name: 'james' },
      { name: 'sam' },
      { name: 'sassms' },
    ],
    edges: [
      { source: 'max', target: 'george' },
      { source: 'george', target: 'jesus' },
      { source: 'jesus', target: 'max' },
      { source: 'jesus', target: 'ben' },
      { source: 'james', target: 'ben' },
      { source: 'sam', target: 'sassms' },
      { source: 'sam', target: 'ben' },
    ],
  });

  return <graph colour="grey" data={data} setdata={setdata} />;
}

function graph(props) {
  function addrandomname() {
    props.setdata({
      ...props.data,
      nodes: [
        ...props.data.nodes,
        { name: math.random().tostring(36).slice(2) },
      ],
    });
  }

  return (
    <react.fragment>
      <button onclick={addrandomname}>add new name</button>
      <h2>names</h2>
      <p> {props.data.nodes.map((d) => d.name).join(', ')}
      </p>
      <h2>state</h2>
      <pre>{json.stringify(props.data, null, 2)}</pre>
    </react.fragment>
  );
}

reactdom.render(
  <react.strictmode>
    <app />
  </react.strictmode>,
  document.getelementbyid('root')
);
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>


Related Query

More Query from same tag