I'm trying to set an object then use it immediately but it is saying that it's null. I can observe in debug mode that the instantiated object is not null.
I could just use the instantiated objected instead of the constant but I was advised not to.
import { useState, useEffect } from "react";
import { loadModules } from "@esri/react-arcgis";
const TestLayer = props => {
const [layer, setLayer] = useState(null);
useEffect(() => {
loadModules(["esri/layers/GraphicsLayer"])
.then(([GraphicsLayer]) => {
const graphicsLayer = new GraphicsLayer();
setLayer(graphicsLayer);
props.map.layers.add(layer); //layer is still null
});
}, []);
return null;
};
export default TestLayer;
Yeah, it's async like the comments suggest. The good news is that where you're trying to access it synchronously is the same place that you have access to the original object, so you can just use it directly:
import { useState, useEffect } from "react";
import { loadModules } from "@esri/react-arcgis";
const TestLayer = props => {
const [layer, setLayer] = useState(null);
useEffect(() => {
loadModules(["esri/layers/GraphicsLayer"]).then(([GraphicsLayer]) => {
const graphicsLayer = new GraphicsLayer();
setLayer(graphicsLayer);
props.map.layers.add(graphicsLayer); // Don't need to access state here
});
}, []);
return null;
};
export default TestLayer;