Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load data from function to state

I have function which load all data from API. I would like to use that function to pass that data to array. But i cannot figured out how to do that.

I have already tried to put that function inside of state of my array, because I do not know how to use that function

function getRoles {
    const url = 'URLTOENDPOINT'
    fetchUtils.fetchJson(url, {
        method: "GET",
    })
    .then(response => {
        Object.keys(response.json.value).forEach(function (key) {
            var object = response.json.value[key];
            names.push(object.Name);
        })
    });
    return names;
}

Simply i want to load data from getRoles function to this array inside state:

class MultipleSelect extends React.Component {
    state = {
      name: [
        'Oliver Hansen',
        'Van Henry',
        'April Tucker'
      ]
    };

...

Expected result should be MultipleSelect with default data loaded from API.

Any ideas how to use that function or what should be improved?

like image 713
Cherry pick Avatar asked Feb 25 '26 15:02

Cherry pick


1 Answers

componentDidMount(){
 this.setState({name:getRoles()})
 }

you can try this way also function return directly set it to state variable

class MultipleSelect extends React.Component {
   state = {
     name: [
      'Oliver Hansen',
      'Van Henry',
      'April Tucker'
  ]
};

 getRoles() {
  const url = 'URLTOENDPOINT'
  var names
  fetchUtils.fetchJson(url, {
  method: "GET",
  })
 .then(response => response.json())
 .then((res) => {
   console.log(res)
  names = res.value.map((data)=>(data.Name))
 })
 return names;
}

componentDidMount(){
  this.setState({name:this.getRoles()})
 }
}
like image 102
Kishan Jaiswal Avatar answered Feb 28 '26 06:02

Kishan Jaiswal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!