Im not understanding why my varaible is undefined, i firstly declare my variable geojsonData as a let so i am able to change the values later in the code. In my useEffect where i use an if statement to check if check if the visibility is true, i set my geojsonData's value. However, in the return of the function my values are not set.
Is there a way i can set the geojson data?
let geojsonData;
...
useEffect(() => {
if(componentVisible == true){
geojsonData = {
type: Type,
features: [
{
type: featuresType,
properties: {},
geometry: {
type: geometryType,
coordinates: coordinate,
},
},
],
};
});
...
return (
<View>
<Geojson geojson={geojsonData}/>
</View>
After a suggestion in the answer section, i have changed my code to use useState hook. However i am still getting an error for type: Type where it "is not assignable to parameter of type '(prevState: undefined) => undefined'." Updated Code:
const[geojsonData, setGeoData] = useState()
...
useEffect(() => {
if(componentVisible == true){
setGeoData({
type: Type,
features: [
{
type: featuresType,
properties: {},
geometry: {
type: geometryType,
coordinates: coordinate,
},
},
],
});
});
...
return (
<View>
<Geojson geojson={geojsonData}/>
</View>
CodePudding user response:
You won't find it effective to change a let variable like that inside a function component. Instead, you should use a useState hook.
const [geojsonData, setGeojsonData] = useState();
//...
useEffect(() => {
if(componentVisible == true){
setGeojsonData(
//include your data here
);
}
},[componentVisible]); //remember to include your dependencies
//...
return (
<View>
<Geojson geojson={geojsonData}/>
</View>
That being said, since you don't appear to actually be getting any new data in your useEffect call, it might be more effective to just use a conditional render:
let geojsonData = //your data
return (
<View>
{componentVisible ? <Geojson geojson={geojsonData}/> : null}
</View>
);
