Reputation: 1
Im developing an app in react native and I have an array called users
Array [
Object {
"occurrences": 42,
"username": "teste0",
},
Object {
"occurrences": 1,
"username": "teste2",
},
Object {
"occurrences": 5,
"username": "teste1",
},
Object {
"occurrences": 0,
"username": "teste 3",
},
]
when I try to put each username in a separate view
async function setUsersView() {
let users;
try {
users = await listUserOcurrences(token);
} catch (e) {
console.log(e);
}
return users?.map((user) => {
return (
<View style={styles.userView}>
<Text style={{ fontSize: 20 }}>
{"\n"} {users.username}
</Text>
</View>
);
});
}
I get the following error Error : Object are not valid as a React child
Upvotes: 0
Views: 96
Reputation: 5700
This is because your setUsersView()
is async
function, which not valid to rendering. Function should be pure function to render some view. So you can do like this :
First create a one state variable to check users is fetched or not, for ex:
const [isLoadingUsers, setLoadingUserStatus] = useState(false); // functional component
// class component
this.state = {
isLoadingUsers: false
}
Now, when you start fetching user toggle it's status to true and render the view based on it's value. For example if user is fetching then you can render ActivityIndicator
or some placeholder and when it's complete the fetch displays the user.
function setUsersView() {
setLoadingUserStatus(true);
let users;
try {
users = await listUserOcurrences(token);
setLoadingUserStatus(false);
} catch (e) {
console.log(e);
}
if (isLoadingUsers) {
return (
<View style={styles.userView}>
<ActivityIndicator animating={true}/>
</View>
)
}
return users?.map((user) => {
return (
<View style={styles.userView}>
<Text style={{ fontSize: 20 }}>
{"\n"} {users.username}
</Text>
</View>
);
});
}
Now, this is simple function and error will gone.
Upvotes: 0
Reputation: 131
users.username here it should be user.username, the callback for map is taking parameter user not users
Upvotes: 1