Cherry pick
Cherry pick

Reputation: 33

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?

Upvotes: 3

Views: 493

Answers (2)

Kishan Jaiswal
Kishan Jaiswal

Reputation: 664

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()})
 }
}

Upvotes: 1

Ckappo
Ckappo

Reputation: 597

Addition to my comment:

 componentDidMount() {
    fetch(
      `https://xxx`,
    )
      .then(res => res.json())
      .then(val=> {
        this.setState({ ... });
      });
  }

Upvotes: 0

Related Questions