Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - FlatList make get request for each item in renderItems

I want to make a get request for each item in my renderItems() so I make it like this:

renderItems({ item }) {
  axios.get(Utilities.url + "Symbol/" + item.Id).then(response => {
    let eachItem = response.data;
  });

  console.log(eachItem);

  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "flex-end",
        alignSelf: "stretch",
        marginRight: 2
      }}
    >
      <Text
        style={{
          color: Colors.WHITE,
          fontSize: 16
        }}
      >
        {eachItem.LVal18AFC}
      </Text>
    </View>
  );
}

But I get the error for:

ReferenceError: eachItem is not defined

I tried to convert the renderItems to an async function and use await but I get another error!

Any solution...?

UPDATE

I used var eachItem = [] outside the axios' then function but now I'm getting:

TypeError: Cannot read property 'LVal18AFC' of undefined!

like image 575
MohamadKh75 Avatar asked Dec 06 '25 04:12

MohamadKh75


2 Answers

@Jigar is correct. Why it is not working: When you call the renderItems function js looks at the asyn call and puts it into its event loop for execution later. It then moves on and logs to your console eachItem which is undefined right now. Then renders your JSX and then executes the async call ( i.e axios request ) when the request serves the data back it is simply store in eachItem which is in the scope of the axios function.

like image 193
Yash Kalwani Avatar answered Dec 08 '25 17:12

Yash Kalwani


you did a bad practice in calling API, what I suggest is, create a separate component for each row you want to display and inside a row call an API you want

so according to your code

class Row extends Component {
    constructor() {
        super()
        this.state = {
            eachItem: null
        }
    }

    componentDidMount() {
        const { item } = this.props;
        axios.get(Utilities.url + "Symbol/" + item.Id).then(response => {
            this.setState({eachItem: response.data});
        });
    }

    render() {
        return (
            <View
                style={{
                    flex: 1,
                    justifyContent: "center",
                    alignItems: "flex-end",
                    alignSelf: "stretch",
                    marginRight: 2
                }}
            >
                <Text
                    style={{
                        color: Colors.WHITE,
                        fontSize: 16
                    }}
                >
                    {this.state.eachItem ? this.state.eachItem.LVal18AFC : null}
                </Text>
            </View>
        );
    }
}
like image 20
Jigar Avatar answered Dec 08 '25 17:12

Jigar