Home > Net >  Can't access data from a dictionary variable in React Native
Can't access data from a dictionary variable in React Native

Time:09-27

I can't access data from a dictionary variable in React Native.

So, I have got my data from the API but can't access it.

This is the Constructor function

constructor() {
    super();
    this.state = {
      url: 'http://127.0.0.1:5000',
      popular: {},
    };
  }

Fetching the data from API here

popularArticle = () => {
    url = `${this.state.url}/popular-articles`;

    axios
      .get(url)
      .then((response) => {
        var data = response.data;
        
        this.setState({popular: data.data})
      })
      .catch((error) => {
        console.error(error.message);
      });
  };

  componentDidMount() {
    this.popularArticle();
  }

The data I Got

{lang:"en",text:"If you want 2017 to be an exciting year, design it that way. That's the advice of former Google career coach and job strategist Jenny Blake , who has helped more than a thousand people improve their work lives. She recommends creating a "mind map," a visual diagram of your interests and goals. Drawing one doesn't take long and could help you figure out the next project, hobby or career change that will make the new year happier and more successful, Blake says. "My favorite way to brainstorm creatively, whether it's about values or setting goals for the new year, is through mind maps," Blake tells CNBC. To make one, write down the year at the center of a piece of paper, and then draw spokes with different themes that are important to you. For example, your spokes could be business, personal life, health and fitness, fun, or skill building. From each of those themes, draw additional spokes to connect the themes to ways you want to improve or experiment in that area. Blake recommends you ask yourself: "What's important to me about that? And what does success look like?" For example, in "personal life," you could write, "Meet up with a friend at least once a month" or "Take a music class." The visual trick works because it helps you see the different ways you can improve, Blake writes in her book " Pivot: The Only Move That Matters Is Your Next One ." "With mind mapping you are taking pen to paper, going old-school," Blake says. And if you're like many professionals who sit too much and stare too long at a computer, drawing might actually be fun. "The goal is to break out of linear thinking," Blake says. "Go broad. Go big. Go sideways, and then experiment to see which of your ideas is most likely to lead to a resonant next step." Video by Andrea Kramar.",title:"former google career coach shares a visual trick for figuring out what to do with your life",total_events:433,url:"http://www.cnbc.com/2016/12/21/former-google-career-coach-shares-a-useful-visual-trick.html"}

I am accessing it like this

render(){
  var article = this.state.popular;

  return (
      <View style={{ flex: 1, padding: 10 }}>
        <StatusBar
          barStyle="dark-content"
          networkActivityIndicatorVisible={false}
        />
        <Text style={{ marginTop: 350 }}>{article.lang}</Text>
      </View>
    );
}

The error I am getting is

TypeError: Cannot read properties of undefined (reading 'lang')

CodePudding user response:

The api takes some time to fetch data and you are rendering your view before getting data from api, so the popular state it empty which dose not have any thing at the starting and that's why it is giving error.

for that you can do it like this

<Text style={{ marginTop: 350 }}>{article ? article.lang : ''}</Text>

or you can show a loader while you fetching data instead of this text view

    ...
    this.state = {
      url: 'http://127.0.0.1:5000',
      popular: {},
      loading: true,
    };


 popularArticle = async () => { //<----add async
    url = `${this.state.url}/popular-articles`;

    await axios //<----add await here
      .get(url)
      .then((response) => {
        var data = response.data; //<-- it return response data
        
         this.setState({
            popular: data.data, //<--- depending on you data object
                    //your data should be like this {data: {..your api data..}}
            loading: false, //<---- set loading false after set data
         })
      })
      .catch((error) => {
        console.error(error.message);
      });
  };
...
<>
  {loading ? <ActivityIndicator size="larg"> :
    <Text style={{ marginTop: 350 }}>{article ? article.lang : ''}</Text>}
</>
  • Related