The last piece of this application is rendering each todo item and providing the ability to change the status of the todo. Let's take a look at this code:
import React, { Component } from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { createFragmentContainer, graphql } from 'react-relay';
import { Text, View, Switch } from 'react-native';
import ChangeTodoStatusMutation from './mutations/ChangeTodoStatusMutation';
import styles from './styles';
const completeStyleMap = new Map([
[true, { textDecorationLine: 'line-through' }],
[false, {}]
]);
class Todo extends Component {
static propTypes = {
viewer: PropTypes.object.isRequired,
todo: PropTypes.object.isRequired,
relay: PropTypes.object.isRequired
};
onValueChange = value => {
const { relay, viewer, todo } = this.props;
ChangeTodoStatusMutation.commit(
relay.environment,
viewer,
todo,
value
);
};
render() {
const {
todo: { text, complete }
} = this.props;
return (
<View style={styles.todoItem}>
<Switch value={complete} onValueChange={this.onValueChange} />
<Text style={completeStyleMap.get(complete)}>{text}</Text>
</View>
);
}
}
export default createFragmentContainer(Todo, {
viewer: graphql`
fragment Todo_viewer on User {
id
}
`,
todo: graphql`
fragment Todo_todo on Todo {
id
complete
text
}
`
});
The actual component that's rendered is a switch control and the item text. When the user marks the todo as complete, the item text is styled as crossed off. The user can also uncheck items. The ChangeTodoStatusMutation mutation sends the request to the GraphQL backend to change the todo state. The GraphQL backend then talks to any microservices that are needed to make this happen. Then, it responds with the fields that this component depends on.
The important part of this code that I want to point out is the fragments used in the Relay container. This container doesn't actually use them directly. Instead, they're used by the todos query in the TodoList component (Todo.getFrament()). This is useful because it means that you can use the Todo component in another context, with another query, and its data dependencies will always be satisfied.