I’m using Leva js to create a simple panel that includes a button that creates an array of random numbers. The length of that array should depends on the property datasetLength
of Leva panel but it seems not to work because of:
Uncaught ReferenceError: Cannot access ‘levaConfig’ before initialization
Here my code:
import { useState } from "react";
import { useControls, button } from "leva";
function App() {
const [dataset, setDataset] = useState<Datum[]>(computeRandomDataset);
const levaConfig = useControls({
"update dataset": button(() => setDataset(computeRandomDataset)),
datasetLength: {
value: 300,
min: 0,
max: 500,
step: 1,
},
});
function computeRandomDataset() {
const datasetLength = levaConfig.datasetLength; // <-- ERROR
return createDataset(datasetLength);
}
return <h1>Vite + React</h1>;
}
export default App;
function createDataset(datasetLength: number) {
const dataset = [];
for (let i = 0; i < datasetLength; i++) {
dataset.push(Math.random());
}
return dataset;
}
2
Answers
I think you are trying to access
levaConfig.datasetLength
before it has been initialized. ThelevaConfig
object is being created asynchronously, and trying to use its properties directly during the initialization of your component can lead to reference errors.To solve this problem, you can use the
useEffect
hook to update the dataset when thedatasetLength
property changes. You can do it like this:This should resolve the reference error you were encountering.
You should try initialising the
levaConfig
const before youruseState
statement. Because youruseState
prop is trying to access thelevaConfig
.