const Sub_Map = () => {
const [isLoading, setLoading] = useState();
const [data, setdata] = useState();
useEffect(() => {
getData();
}, []);
const getData = () => {
fetch('http://. . . . /aplikasi/restapi.php?op=getJenis')
.then(res => res.json())
.then(json => setdata(json))
.catch(error => alert(error))
.finally(setLoading(false));
};
on the "data.map" there is an error, please explain for me
return (
<View style={styles.container}>
<Text style={styles.text}>Pilih Data</Text>
<View style={styles.picker}>
{isLoading ? (
<ActivityIndicator />
) : (
<Picker
selectedValue={data}
onValueChange={itemValue => setdata(itemValue)}>
{data.map((item, key) => {
<Picker.Item
label={'${item.bencana}'}
value={'${ item.id }'}
key={key}
/>;
})}
</Picker>
)}
</View>
);
};
please help me, i’m still newbie about react native TypeError:
undefined is not an object (evaluating ‘data.map’)
3
Answers
Write it like this, and it will work:
Best guess from the code snippet is that you are rendering before data is populated.
I would try something like this;
What the above code is doing is calling your API and once it’s done, it sets the hasLoaded state to true – indicating it is finished.
Then in the return, you notice I return it conditionally based on that state. So nothing will render until the API call is done.
I also amended your data mapping to allow for undefined cases.
You have not initialised the states, I guess that is the problem.
Do this :