Search code examples
reactjsaxios

Components within a component cannot get values


I have a component that loads user information through axios:

const [isEditingFirstName, setIsEditingFirstName] = useState(false);
const [firstName, setFirstName] = useState('');
const [isEditingLastName, setIsEditingLastName] = useState(false);
const [lastName, setLastName] = useState('');

const [userInfo, setUserInfo] = useState(null);
const [favoriteTrainings, setFavoriteTrainings] = useState([]);
const [favoritePrograms, setFavoritePrograms] = useState([]);

const Axios2 = axios.create({
    baseURL: "http://localhost:4444/",
    withCredentials: true,
});

useEffect(() => {
    // Отримання даних про користувача
    Axios2.get('http://localhost:4444/userinfo')
        .then(response => {
            setUserInfo(response.data);
            setFavoriteTrainings(response.data.favoriteTrainings);
            setFavoritePrograms(response.data.favoritePrograms);
        })
        .catch(error => {
            console.error('There was an error!', error);
        });
}, []);

Inside the return method there are components elements that immediately update their value. However, I have several components that are created inside this component:

            <EditableText id="age" label="Age" placeholder="Age" type="number"
                          initialValue={userInfo ? userInfo.weight  : 'Loading...'} style={{flex: 1}}/>
            <EditableText id="weight" label="Weight" placeholder="Weight" type="number"
                          initialValue={userInfo ? userInfo.weight : 'Loading...'} style={{flex: 1}}/>
            <EditableText id="height" label="Height" placeholder="Height" type="number"
                          initialValue={userInfo ? userInfo.height : 'Loading...'} style={{flex: 1}}/>
            <EditableText id="callisthenics" label="Callisthenics" type="select"
                          options={['Beginner', 'Intermediate', 'Advanced']}
                          initialValue={userInfo ? userInfo.experience : 'EditableText'} style={{flex: 1}}/>

Inside them I pass some values inclusive of the ones they should display. As a result, after the component is loaded, all these EditableText have the value “Loading” while the html components initially present on the page can get the values from userInfo.


Solution

  • It seems to me that this promise isn't returning anything. Refer to this question :Returning data from Axios API