Invalid Context after useState #226
-
Hey, I want to send a command to Unity with "unityContext.send". This is works great, until I load some JSON from an API and set it as a state variable. Below is the working code. If I uncomment the "fetchData();" it is not working anymore. How can I solve this? const [myContent, setMyContent] = useState([]);
async function fetchData() {
const response = await fetch('https://localhost:5001/Data/MyContent');
const fetchedData = await response.json();
setMyContent(fetchedData); //<-------------------- This is causing the problem
}
const unityContext = new UnityContext({
loaderUrl: "/unity/Build.loader.js",
dataUrl: "/unity/Build.data.br",
frameworkUrl: "/unity/Build.framework.js.br",
codeUrl: "/unity/Build.wasm.br"
});
useEffect(() => {
//fetchData(); //<-------------------- After uncommenting this, "unityContext.send" is not working anymore
}, []);
const setProduct = () => {
unityContext.send("Receiver", "SetProduct", 1);
}
return (
<div>
<Button onClick={() => setProduct()}>Test</Button>
<Unity style={{height: 500, width: "80%", background: "grey"}} unityContext={unityContext}/>
</div>
); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi. Each re-render results into the execution of the function component. This means that the unityContext keeps being recreated. You can either create create it outside of your component, or within a "componentDidMount" cycle using a useEffect without any dependencies. I hope this helps you! Happy coding. |
Beta Was this translation helpful? Give feedback.
Hi. Each re-render results into the execution of the function component. This means that the unityContext keeps being recreated. You can either create create it outside of your component, or within a "componentDidMount" cycle using a useEffect without any dependencies. I hope this helps you! Happy coding.