Still on the learning curve with React Native. I have read the Realm docs and other forums but cannot seem to find the answer to the seemingly simple notion of writing data to a Realm. For example;
In my code, I receive the data (list of users) from a local json file and am able to access and display their information.
The bit i'm struggling with is the onPress function bookmarkItem
. Where on button press I want to realm.write
certain data from a json file to Realm. How do i store the value of say {{user.login.username}}
in my realm database??? Below is the code in question;
import { users } from '../config/data';
import Realm from 'realm'
class Article {}
Article.schema = {
name: 'Article',
properties: {
key: 'data',
image: 'data',
title: 'data',
}
};
let realm = new Realm({schema: [Article]});
class Feed extends Component {
onLearnMore = (user) => {
this.props.navigation.navigate('Details', { ...user });
};
bookmarkItem = (user) => {
realm.write(() => {
realm.create('Article', {
key: {{user.login.username}},
image: {{ uri: user.picture.large}},
title: {{user.name.first}},
});
});
};
render() {
return (
<ScrollView>
{users.map((user) => (
<Card key={user.login.username}>
<CardItem header>
<Right>
<Button onPress={() => this.bookmarkItem(user)}>
<Icon name="bookmark" />
</Button>
</Right>
</CardItem>
<CardItem cardBody onPress={() => this.onLearnMore(user)}>
<Image source={{ uri: user.picture.large }}/>
</CardItem>
<CardItem content>
<Text>{user.name.first} {user.name.last}</Text>
</CardItem>
</Card>
))}
</ScrollView>
);
}
Clearly I'm not understanding something with the use of schema data types and how and where to correctly execute my realm.write function. Any help would be greatly appreciated. Cheers
You don't have to use {{}}
outside the JSX elements in your render function. Instead of {{user.login.username}}
just use user.login.username
in your realm.create
function.
Also for image you shouldn't use uri: user.picture.large
just user.picture.large
will be enough. You can later use that variable as a uri.