Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't know how to get data from fetch correctly

I have a Users class where I want to get data from the server for later writing it to state and passing data from state to the child component

export default class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: this.getUsers(),
    };
  }

  getUsers = async () => {
    await return fetch(`http://localhost:3001/users`, {
      method: 'POST',
      accept: 'application/json'
    }).then(res => {
      if(res.ok) {
        res.json();
      }
    })
  }
}

this is what the console shows me when I output data about this.state.users

enter image description here

I tried to look for similar situations, but I didn't find anything worthwhile, so I ask for help here. I would be grateful for any advice or help. I'm only learning asynchrony in js

like image 696
Святослав Марюха Avatar asked Jan 17 '26 06:01

Святослав Марюха


2 Answers

if you use async await, you don't have to pass callback function, just await the promises and update the state incase of successful response.

getUsers = async () => {
    try {
       const response =  await fetch(`http://localhost:3001/users`, {
         method: 'POST',
         accept: 'application/json'
       });

       const users = await response.json();

       this.setState({ users });

     } catch (error) {
       console.log(error);
    }
 }

and instead of calling getUsers function from the constructor, use componentDidMount

componentDidMount() {
    this.getUsers();
}

and your state should be initially null or an empty array

this.state = {
  users: []
};
like image 118
Yousaf Avatar answered Jan 19 '26 18:01

Yousaf


Add componentDidMount and call getUsers and set state.

this.state = {
  users: [],
};

getUsers = async () => {
  return await fetch(`http://localhost:3001/users`, {
    method: 'POST',
    accept: 'application/json'
  }).then(response => response.json())
   .then(res => { this.seState({ users: res })})
   .catch(e => { console.log(e)})
}

componentDidMount = () => {
  this.getUsers()
    .catch(e => console.log(e)
}
like image 20
TenTen Peter Avatar answered Jan 19 '26 19:01

TenTen Peter