I've got 1/ an infinite loop using a useState to save a data from an axios request. I want to inject the value in a view during a mapping :
import { StyleSheet, Text, View, TextInput, FlatList, Button, ScrollView } from 'react-native';
import styles from './styles'
import React, { useEffect, useState, Component } from 'react';
import App, { currentCityCode } from './app'
import axios from 'axios';
import { Dropdown } from 'react-native-material-dropdown';
function Chat(props) {
useEffect(() => {
getMessage()
}, []
);
const messApiRest = "https://..."
const [lastMessage, setLastMessage] = useState("")
const [user, setUser] = useState("")
const [categoryMessage, setcategoryMessage] = useState("")
const [idUser, setIdUser] = useState("")
const [allMessages, setAllMessages] = useState([])
const [messageOneByOne, seMessageOneByOne] = useState([])
function getMessage() {
axios.get(messApiRest + "/api/messages",
{
headers: {
'Authorization': "Bearer " + props.token,
},
params: {
'citycode': props.cityCode
},
})
.then(response => {
setAllMessages(response.data.results)
},
)
}
function getUserName(toto) {
axios.get(messApiRest + "/api/users/" + toto,
{
headers: {
'Authorization': "Bearer " + props.token,
}
}
)
.then(response => {
console.log(response.data.username)
setUser(response.data.username)
})
}
return (
<View style={styles.container}>
{allMessages.map(function (message) {
getUserName(message.author.id)
return (
<Text>{user}: {message.content}</Text>
)
})}
</View>
)
}
export default Chat
The main problem is that if a save my {user} using a useState, i create an infinite loop.
2/ I've tried avoiding that by not saving it with the useState, and directly return the value response.data.username in the view, but it doesn't work. I know I can't return the value of a promise, that's why I'm using a useState instead.
I'm a begginer {probably not a good one}, I'm trying to understand how React and axios works, but i'm at my limit and can't guess a solution...
Thank you for your help, if someone dare ^^