eccck
eccck

Reputation: 7

React-native array data assignment with fetch

I am developing a mobile app in react- native as a beginner. I have a little problem while using react-native. let me explain it in detail, what I am trying to do is fetching data from Restful api and assign this data to array in react. Below is my code to fill array data.

function getMoviesFromApiAsync() {
 return fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json())
.then((responseJson) => {
  return JSON.stringify(responseJson)
})
.catch((error) => {
  console.error(error);
});
}
const initialState = {
 data: getMoviesFromApiAsync();
  };

export default (state = initialState,action ) => {
  return state;
};

Above is all my .Js file and it does not has class declaration.

Any help ??

Upvotes: 0

Views: 2708

Answers (1)

Tholle
Tholle

Reputation: 112897

You can create a class component with the initial state of data as an empty array, and then get the real data in the componentDidMount hook and put it in state.

Example

function getMoviesFromApiAsync() {
  return fetch("http://localhost:8080/JweSecurityExample/rest/security/retrieveItems")
    .then(response => response.json())
    .catch(error => {
      console.error(error);
    });
}

class App extends React.Component {
  state = {
    data: []
  };

  componentDidMount() {
    getMoviesFromApiAsync().then(data => {
      this.setState({ data });
    });
  }

  render() {
    return <div>{JSON.stringify(this.state.data)}</div>;
  }
}

Upvotes: 1

Related Questions