15

I'm developing a little app in React Native and I am looking for something like a foreach function. I just can't find a foreach loop. Not on StackOverflow and not even in the docs. I've found something with 'map', but I don't know if this is what I'm looking for.

With a request to my Server I get multiple objects of users. When I log the result, it looks like this:

Object {
    "id": "1",
    "role": "user",
    "username": "user1",
  },
Object {
    "id": "2",
    "role": "admin",
    "username": "user2",

I'd like to output this to a list. In plain PHP I would use a foreach loop for this, but like I said, I can't find a foreach loop for React Native.

How is it possible to loop trought this objects? I know that I could also use a simple for loop, but this would definitly not be my first choice...

EDIT: I saved this value in this.state.users with this.setState({users: responseData.users});. State is defined in my constructor. I try to access this with this.state.users.map(id => <Text>{id}</Text>) but I always get the same error: null is not an object (evaluating 'this.state.users.map'). Am I doing this right?

0

4 Answers 4

35

You can use map or for-of or any other

Example:

// for of
for (let userObject of this.state.users) {
    console.log(userObject.username);
}
// map
this.state.users.map((userData) => {
    console.log(userData.username);
});

as per the error you may not have data within users state, so you are getting error. If data is proper then above example will work properly

Sign up to request clarification or add additional context in comments.

1 Comment

getting an error like forEach and i tried to solve out but there is another errors are occured so this can't help but thanks for response
15

In react, preferred way is map method of Array. Example using ES6 arrow function:

render() {    
    return (
        <View>    
           {dataList.map(r => <Button>{r}</Button>)}    
        </View>
    )
}

1 Comment

I get null is not an object (evaluating 'this.state.users.map'). FYI I've also updated my question.
0

You can also use lodash (npm install lodash) and run the following:

import _ from 'lodash';

...

_.each(dataList, function(userObject, key) { console.log(userObject, key); });

1 Comment

This is quite over-engineered.
0
import React, { useContext, useState } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";
import BlogContext from "../context/BlogContext";

export default function IndexScreen() {

  const blogPosts = useContext(BlogContext);

  return (
    <View>
      {blogPosts.map((post) => {
        return <Text>{post.title}</Text>;
      })}
    </View>
  );
}

Comments

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.