could you please tell me how send data from component to worker on button click?
I tried like that not working
// xx.postMessage([first.value,second.value]);
could you please suggest where i am doing wrong .I want to do some background calculation and return result to component.
here is my code
import React, { useEffect } from "react";
import "./styles.css";
import worker from "./workerfile";
import WebWorker from "./setup";
export default function App() {
const buttonHan = () => {
alert("==g=");
// xx.postMessage([first.value,second.value]);
//console.log("Message posted to worker");
};
useEffect(() => {
let xx = new WebWorker(worker);
//xx.addEventListener("message", event => {
// });
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox1</h1>
<button onClick={buttonHan}>BTN</button>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
code
https://codesandbox.io/s/bold-forest-s3guc?file=/src/App.js:212-263
This is the way i'd do it, idk if it's the supreme right way but i haven't had any problem declaring vars like this.
Also it's extremely useful when it comes to work with third party event handlers
export default function App() {
let xx = new WebWorker(worker); // Declare worker
// Constants declarations
const buttonHan = () => {
alert("==g=");
xx.postMessage("[first.value,second.value]");
console.log("Message posted to worker");
};
useEffect(() => {
xx.addEventListener("message", event => {
console.log(event)
});
}, [xx]); // useEffect executes when worker is setted
// this should be done even if variable is not a state
...
Related
i have a react component thats keep re-rendering idk why but i think the reason is the data fetching
data code :
export function KPI_Stock_Utilisation() {
const [kpi_stock_utilisation, setKpi_stock_utilisation] = useState([{}]);
useEffect(() => {
axios.get("http://localhost:5137/KPI_Stock_Utilisation").then((response) => {
setKpi_stock_utilisation((existingData) => {
return response.data;
});
});
}, []);
console.log('data get')
return kpi_stock_utilisation;
}
this log displayed many times , and the log in the component too
component code :
import React from "react";
import { KPI_Stock_Utilisation } from "../../Data/data";
import { useEffect } from "react";
export default function WarehouseUtilisChart(props) {
let kpi_stock_utilisations =KPI_Stock_Utilisation();
let Stock_utilisation = (kpi_stock_utilisations.length / 402) * 100;
console.log('component render')
return (
<div>
<p>{kpi_stock_utilisations}</p>
</div>
);
}
im new with react i tried useEffect inside the componenets but its not working
Calling the react custom hook KPI_Stock_Utilisation several times will for sure render more than once.
in your case I suggest you use useEffect in the same component as I will show you.
import React,{useEffect,useRef} from "react";
import { KPI_Stock_Utilisation } from "../../Data/data";
import axios from 'axios';
export default function WarehouseUtilisChart(props) {
const [kpi_stock_utilisation, setKpi_stock_utilisation] = useState([{}]);
const stock_utilisation= useRef(0);
useEffect(() => {
axios.get("http://localhost:5137/KPI_Stock_Utilisation").then((response) => {
stock_utilisation.current = (response.data.length / 402) * 100;
setKpi_stock_utilisation(response.data);
});
//this will guarantee that the api will be called only once
}, []);
//you should see this twice, one with the value 0, and another one, the calculated data
console.log('component render',stock_utilisation.current)
return (
<div>
<p>{kpi_stock_utilisations}</p>
</div>
);
}
To note, if you call this component from more than one location, for sure it will render several times - keep that in mind.
On the other hand, all your variables should always start with a lower case and try to name your variables like this: instead of kpi_stock_utilisation change it to kpiStockUtilisation for a better coding practice
You got into infinite loop.
Its hard to explain why it doesn't work as expected, but I can try.
First of all, useEffect with empty array of dependencies works like componentDidMount and fires only after (!) first render.
So you have some value returned from your let kpi_stock_utilisations =KPI_Stock_Utilisation(); then it rendered, after this your useEffect fires a request and set state, setting of state trigger re-render and new value to return, this new value trigger your parent component to return let kpi_stock_utilisations =KPI_Stock_Utilisation(); might run again.
If you are trying to create a custom hook for fetching some info, follow rules of hooks
I hope it helped you
Im new in react.
I'm Created two file App.js and UseEffect.js
I'm Learn about lifecycle in react with function.
So When I See in console, that's render multiple time.
You can see my picture below.
My Console In Browser
This Is My Code
UseEffect.js
import React, {useState, useEffect} from "react";
function MyFunction(){
console.log('-> Function Init')
const [count, setCount] = useState(0)
const handleCount = () => {
setCount(prevState => {
return prevState+1
})
}
//LifeCycle
useEffect(() => {
console.log('my first effect')
})
console.log(`-> Start Render (${count})`)
return(
<div>
<h1>Function Component</h1>
<p>
<button onClick={handleCount}>Count</button>
{count}
</p>
</div>
)}
export default MyFunction
App.Js
import './App.css';
import UseEffect from './components/UseEffect'
function App() {
return (
<div className="App">
<UseEffect />
</div>
);
}
export default App;
How do it's work?, I Want it. it's just render one times.
Your useEffect call is missing a dependency array. When you want it to run only at the initial render, you need to pass it an empty array as its dependencies.
useEffect(() => {
console.log('my first effect')
}, [])
For further details, see this question.
Why it renders twice:
It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place.
-gaearon
TLDR: It's a feature not a bug.
Although the text gets updated on the page, the console.log still logs out the initial value. Why is this? I know that setting the state is asynchronous but why does it still log out the old value even after waiting 1 second?
import { useState, useEffect, useRef } from "react";
function App() {
const [requestState, setRequestState] = useState("initial");
useEffect(() => {
setRequestState("changed");
setTimeout(() => {
console.log(requestState);
}, 1000);
}, []);
return (
<div className="App">
{requestState}
</div>
);
}
export default App;
useEffect will run when the component renders,To call a function conditionally, specify the list of dependencies.
And the rule of thumb is to always add those dependencies that you are using inside the useEffect()
import { useState, useEffect, useRef } from "react";
function App() {
const [requestState, setRequestState] = useState("initial");
setRequestState("changed");
useEffect(() => {
setTimeout(() => {
console.log(requestState);
}, 1000);
}, [requestState]);
return (
<div className="App">
{requestState}
</div>
);
}
export default App;
The useEffect() hook "captures" state and props when it is executed. That is why it has a stale value. The value is from when the function in useEffect() was run.
This is a beautiful article by Dan Abramov: https://overreacted.io/a-complete-guide-to-useeffect/. It has an explanation about almost the exact same problem as yours. Read it completely to have a great insight into useEffect()
Your useEffect depends on the requestState varible, so pass it inside the empty list like so:
useEffect(() => {some code},[used variables])
I’m implementing a rich text editor into a NextJS project. There are no React components for it, and it runs only on the client side, so I have to load the JavaScript and CSS files from an external source and work around SSR. Please don't recommend to use another tool, as that is not an option.
The tool works fine as a class component, but I’d like to port it into a functional component. When I test the functional component, it works occasionally — namely, after I change my file and save (even if it's just adding a space). But as soon as I refresh the page, I lose the editor. I thought it was because the component hadn’t mounted, but now I check for that, yet the issue persists.
I’ve tried various approaches, including Next’s Dynamic import with SSR disabled, but so far only the class method below has worked (the editor works by binding to the <textarea> element):
import React from "react";
import Layout from "../components/Layout";
class Page extends React.Component {
state = { isServer: true };
componentDidMount() {
this.MyEditor = require("../public/static/cool-editor.js");
this.setState({ isServer: false }); // Trigger rerender.
var app = MyEditor("entry"); // Create instance of editr.
}
render(props) {
return (
<Layout>
<textarea id="entry"></textarea>
</Layout>
);
}
}
export default Page;
Last attempt at functional component:
import React, { useEffect } from "react";
import Layout from "../components/Layout";
function hasWindow() {
const [isWindow, setIsWindow] = React.useState(false);
React.useEffect(() => {
setIsWindow(true);
return () => setIsWindow(false);
}, []);
return isWindow;
}
const Editor = () => {
useEffect(() => {
const script = document.createElement("script");
script.src =
"http://localhost:3000/static/article-editor/cool-editor.js";
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
var app = MyEditor("entry");
return (
<Layout>
<textarea id="entry"></textarea>
</Layout>
);
};
const Page = () => {
const isWindow = hasWindow();
if (isWindow) return <Editor />;
return null;
};
export default Page;
You can use useRef hook in <textarea> tag:
const refContainer = useRef(null);
return <textarea ref={refContainer}>
then useEffect to check if the the element has been mounted.
useEffect(() => {
if (refContainer.current) {
refContainer.current.innerHTML = "ref has been mounted";
console.log("hello");
}
}, []);
Check the code here: https://codesandbox.io/s/modest-dubinsky-7r3oz
Some of the things I could suggest changing:
var app = MyEditor("entry"); is being created on every render. Consider using useRef as a way to keep instance variable: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
In Editor, the MyEditor variable is not defined.
hasWindow includes a useEffect that runs once (with empty dependency array), I don't think it needs the clean up function. To check staying at browser or server, you could simply use const isServer = type of window === 'undefined'
Custom hook should be named with prefix use
I am trying to use webworker in our demo application, but I am not able to create instance of my worker. I get the error worker` is read only. Why?
Here is my code
https://codesandbox.io/s/bold-forest-s3guc?file=/src/App.js
import React, { useEffect } from "react";
import "./styles.css";
import worker from "./workerfile";
import WebWorker from "./setup";
export default function App() {
const buttonHan = () => {
alert("==g=");
};
useEffect(() => {
// worker = new WebWorker(worker);
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={buttonHan}>BTN</button>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
The iissue is when I am creating a object of worker in useEffect in the below line.
// worker = new WebWorker(worker);
On button click, I want to send trigger to my worker for calculation.
You have two lines that are in conflict.
import worker from "./workerfile";
and
// worker = new WebWorker(worker);
You first import from a file and assign the value to a variable named worker.
You should not then later change that value. If you must use that name you can shadow-scope your variable by including a block-scope keyword such as let or const. But you can also just redefine the variable name (e.g. myWorker or similar).
The const value worker is the default export and therefore readonly. I assume you want to use the worker object for the creation of the WebWorker.
Just remove the part where you are storing the created WebWorker in the worker constant variable.
import React, { useEffect } from "react";
import "./styles.css";
import worker from "./workerfile";
import WebWorker from "./setup";
export default function App() {
const buttonHan = () => {
alert("==g=");
};
useEffect(() => {
new WebWorker(worker);
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={buttonHan}>BTN</button>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}