0

I was wondering how can I get json data from using the fetch API and then display it without using the data= from the Lists(Flatlist, ListView, etc.). I am thinking about something like this:

    export default class HomeScreen extends React.PureComponent {
    constructor(props)
{

  super(props);

  this.state = {
  isLoading: true,
};

componentDidMount(){
     fetch(`http://www.example.com/React/data.php`, {
     method: 'POST',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/json',
     },
   }).then((response) => response.json())
       .then((responseJson) => {

      data = responseJson;
      this.setState({ loading: false });


   }).catch((error) => {
     console.warn(error);
   });

}

renderItems() {
  const items = [];
  this.data.foreach( ( dataItem ) => {
    items.put( <Text>{ dataItem.id }</Text> );
  } )
  return items;
}

render() {


    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }


      return(

         <View style = { styles.MainContainer }>
          <View>
           <Card>          
              <View>
              <Text>{this.renderItems()}</Text>
             </View>
           </Card>
           </View>
         </View>
       );
     }
const styles = StyleSheet.create({
  MainContainer: {
    flex:1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#333',
  },
     }

I am sure not exactly how it should look, but if there is a way to do this then my guess to do something like that? Any help is always appreciated!

Here is the response for the data:

Here is the response of the data:

{"id":"1","imagename":"dog"}{"id":"2","imagename":"cat"}{"id":"3","imagename":"mouse"}{"id":"4","imagename":"deer"}{"id":"5","imagename":"shark"}{"id":"6","imagename":"ant"}
3
  • Ok so a few things first... Are you looking at JSON data with a single item? Or is it an array of items? Commented May 20, 2018 at 3:52
  • @NemiShah Just a single item: {"id": "13", "imagename": "hello"} Commented May 20, 2018 at 4:10
  • Ok my explanation was longer than i expected, so posted an answer. Commented May 20, 2018 at 4:30

2 Answers 2

1

This is something that worked for me.

add state in constructor

  constructor(props) {
    super(props);
    this.state = {
      dataSource: ""
    };
  }

Then normally fetch data no matter how you are fetching data whether it's in lifecycle method or normal func. Just do setState to dataSource that we created before

componentDidMount() {
    const data = new FormData();
    data.append("get_about", "true");
    fetch("https://www.example.com/api/About", {
      method: "post",
      body: data
    })
      .then(response => response.json())
      .then(responseJson => {
        this.setState({                                // ++++
          dataSource: responseJson                     // ++++
        });                                            // ++++
        console.log(dataSource);
      });
  }

Now, just call it by :

render() {
    return (
      <View style={styles.container}>
        <Text>{this.state.dataSource.about_info}</Text>
      </View>
    );
  }
Sign up to request clarification or add additional context in comments.

Comments

0

So this is something I would do, and is not necessarily the best method.

componentDidMount(){
 fetch('http://www.example.com/React/data.php', {
 method: 'POST',
 headers: {
   'Accept': 'application/json',
   'Content-Type': 'application/json',
 },
 body: JSON.stringify({
   id : ?,
   imagename : ?,

 })

 }).then((response) => response.json())
     .then((responseJson) => {

      this.data = responseJson;
      this.setState({ loading: false });


 }).catch((error) => {
   console.error(error);
 });

Where 'data' is a local Object in your component class, and loading is just a flag to know when the data is to be rendered.

Then your render method would look like

...
{ !this.state.loading &&
    <View>
      <Text>{ this.data.id }</Text>
      <Text>{ this.data.imagename }</Text>
    <View>
}
...

The rendered component can ofcourse change to whatever you like, but this will handle when to show your item and the data can be accessed from anywhere inside the component class.

NOTE: You could also keep data inside state and skip the loading flag, but this is how I normally do it.

Additionally if ever you want to do the same thing in a case where your JSON data has an array of items, you can do something like this.

Lets say your JSON response is

{
  [
   {
    title: 'title1'
   },
   {
    title: 'title2'
   }
  ]
}

Do the similar steps to have your data in a local Object. Create a method like

renderItems() {
  const items = [];
  this.data.foreach( ( dataItem ) => {
    items.put( <Text>{ dataItem.title }</Text> );
  } )
  return items;
}

And then in your render method

...
{ this.renderItems() }
...

Hope this helps.

11 Comments

When I tried the first code above, I got a syntax error so I removed the JSON.stringify. Then came another error: undefined is not an object (evaluating '_this5.data.id') also to note I have more than one of that example data in my comment. Just in case that might be the cause of it.@NemiShah
So the code has a few gaps in it but I couldn't give you the full answer without a proper sample of the response... Or if you can give me the URL you are hitting I can go through the response my self
Sorry about that, I updated my question above and pasted all of the data from the json file
Ok so I'm assuming your json data is an array with all of those individual objects inside it. In that case you can use the second part of my answer
I used the second answer and I made sure ever detail was correct. I kept getting this error: undefined is not an object (evaluating 'this.data.foreach')
|

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.