Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

component is being duplicated in react

component is getting duplicate on screen on each useState change even if i add depencancy in useEffect

how can we avoid mounting and how cac we update existing component

here im facing the issue

im using a external library in react application

I'm using yasgui library for sparql query editor in react application this is the code im using for updating the yasqui(yasr) response result

I'm targeting a element directly by using getElementById

 const [result , setResult] = React.useState([])
    React.useEffect(( )=>{
    var yasr = new YASR(document.getElementById("yasr"), {
     getUsedPrefixes: {},
          drawOutputSelector: true,
          drawDownloadIcon: false,
    }
     yasr.setResponse({
          data: result.data,
          contentType: "application/sparql-results+json",
          status: 200,
         executionTime: 1000,
        });
    },[ result ])

element

<div id ="yasr" ></div>

how can we update the yasr results without rendering(duplicate) component while useState change if i got any help that is so appricatable

thankyou

like image 531
jsBug Avatar asked Aug 12 '26 20:08

jsBug


2 Answers

I think the issue is that you are trying to use a single useEffect hook to create/attach to the element and update the data, with a dependency on the result state. Each time the result state updates a new YASR object is created.

Split the logic into two effects: (1) a mounting effect to create the YASR object once and (2) an effect to update the data when the result state updates. Use a React ref to store the YASR instance.

Example:

const [result , setResult] = React.useState([]);
const yasrRef = React.useRef();

React.useEffect(() => {
  const yasr = new YASR(
    document.getElementById("yasr"),
    {
      getUsedPrefixes: {},
      drawOutputSelector: true,
      drawDownloadIcon: false,
    },
  );

  yasrRef.current = yasr;
}, []);

React.useEffect(() => {
  yasrRef.current.setResponse({
    data: result.data,
    contentType: "application/sparql-results+json",
    status: 200,
    executionTime: 1000,
  });
}, [result]);
like image 134
Drew Reese Avatar answered Aug 15 '26 09:08

Drew Reese


I think you can achieve what you want by setting a ref pointing to the YASR class/object.

Then you can use or reference to YASR wherever you want in your code.

In that way you just instantiate YASR once and then you use it whenever you want and it's not dependant on the state changes.

const yasrRef = React.useRef()
    React.useEffect(() => {
    // init YASR
    yasrRef.current = new YASR(document.getElementById("yasr"), {
      getUsedPrefixes: {},
      drawOutputSelector: true,
      drawDownloadIcon: false,
}
  }, [])
like image 39
victor.ja Avatar answered Aug 15 '26 11:08

victor.ja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!