0

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 ??

0

1 Answer 1

1

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>;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@eccck Alright. Consider opening up another question if you can't figure it out.
Actually no need for another question, simply I need to get data variable outside of class declaration, but still I have not figured out how to do it. @tholle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.