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
CodePudding user response:
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]);
CodePudding user response:
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,
}
}, [])