Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react fetch data on button click

I'm trying to fetch data in react. The problem is i have to click on button twice to get that data. Although i don't get data on first click it somehow renders if I add JSON.stringify to it. If I don't add JSON.stringify it returns undefined. If anyone know what this is please help me

without clicking
on first click
on second click

import React, {useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'

function Example() {

const [students,setStudents] = useState('')
const [name,setName] = useState('')

const handleClick = async() => {
    const data = await axios.get('api/foo')
    setStudents(data)
    console.log(students)
}

return (
    <div className="container">
        <h2>Example component</h2>
        <button onClick = {handleClick}>Get students</button>
        <div>
            {JSON.stringify(students.data)}
        </div>
    </div>
);
 }

export default Example;

if (document.getElementById('root')) {
     ReactDOM.render(<Example />, document.getElementById('root'));
 }
like image 480
Artsiom Aliaksandrau Avatar asked Sep 02 '25 08:09

Artsiom Aliaksandrau


1 Answers

The problem was that setStudents is an asynchronous function, so I just made student object and added to it loading property

const [students,setStudents] = useState({
    data: '',
    loading: true
})
const [name,setName] = useState('')

const handleClick = async() => {
    const data = await axios.get('api/foo')
    setStudents({
        data: data,
        loading: false
    })
}

return (
    <div className="container">
        <h2>Example component</h2>
        <button onClick = {handleClick}>Get students</button>
        <div>
            {students.loading?'':
            students.data.data[0].name}
        </div>
    </div>
);

}

like image 75
Artsiom Aliaksandrau Avatar answered Sep 04 '25 21:09

Artsiom Aliaksandrau