I have a component in react native that gets data from mongodb
const Num = () => {
console.log("how many times do you see this message?")
const [data, setData] = useState([])
const [loading,setloading] = useState(true)
const url = "http://localhost:3100/cuentas"
useEffect(()=>{
fetch(url)
.then((response)=>response.json())
.then((json)=>setData(json))
.catch((error)=>console.error(error))
.finally(()=>setloading(false))
},[])
return(
<View style={styles.sectionContainer}>
{loading ? ( <Text>Loading....</Text>) : (
data.map((post,xid)=>(
<TouchableOpacity key={xid} style={styles.button}><Text style={styles.text}>#{post._id.slice(-2)}</Text></TouchableOpacity>
))
)}
</View>
)
}
Then i put the component into another component to set the multiple items into a scrollView
const Notas = () => {
return(
<ScrollView Style={styles.container}>
<View style={styles.sectionContainer}>
<Num></Num>
</View>
</ScrollView>
)
}
But the problem here is that it doesn't apply the map one time,it does it 3 times and you can see it by the console.log that is set first at the Num component
I've been debugging and i find that if i remove the .then's it doesn't repeat the map function 3 times, i tried to put the whole funcion inside the useEffect but i get an error that said "useEffect must not return anything besides a function"
If some one have a tip, it could be useful.
Try using async await:
useEffect( async ()=>{
await fetch(url)
.then((response)=>response.json())
.then((json)=>setData(json))
.catch((error)=>console.error(error))
.finally(()=>setloading(false))
},[])