'Populate a picker from code - React native
Using the component https://github.com/react-native-picker/picker, I am trying to create a dropdown list which uses values from an API. I found the article on https://alexb72.medium.com/how-to-populate-react-native-picker-dynamically-with-values-from-an-api-dbe122e85a5a, which aims to do the same. However, it throws erros right at the start, just by creating App.js:
ERROR ReferenceError: Can't find variable: React
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
I am running in Android Emulator. Does anyone have a working project?
Solution 1:[1]
The reason it didn't work is that the article uses an old version of react native. Instead of this: "class App extends React.Component {", we are now using "const App = () => {". Other parts of the code throw error too because of the outdated nomenclature.
I got the list to work, however it can only be loaded by pressing a button. In the old versions of react native there was a function called componentDidMount, but it cannot be used now, and setting state in the constructor will render the page in an infinite loop. Do you know what the new lifecycle methods are? I haven't found any documentation of them.
Here is my code:
import * as React from 'react';
import { useState } from 'react';
import { Button, SafeAreaView } from 'react-native';
import { Picker } from '@react-native-picker/picker';
const App = () => {
const [users, setUsers] = useState();
async function req() {
let userValues = await fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json());
setUsers(userValues.map((myValue,myIndex) => {
console.log('User: ' + myValue.name + " - " + myIndex);
return(
<Picker.Item label={myValue.name + ' - ' + myValue.username} value={myIndex} key={myIndex}/>
)
}))
}
return (
<SafeAreaView>
<Button
color='green'
title="Load users"
onPress={() =>
req()
}
/>
<Picker
mode="dialog"
onValueChange={(itemValue, itemIndex) =>
{
}}>
{users}
</Picker>
</SafeAreaView>
);
}
export default App;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Balint Fodor |
