Skip to content

Instantly share code, notes, and snippets.

@andyjessop
Last active May 7, 2020 22:34
Show Gist options
  • Save andyjessop/678c803d8eebdba22d73fccc0b000d5b to your computer and use it in GitHub Desktop.
Save andyjessop/678c803d8eebdba22d73fccc0b000d5b to your computer and use it in GitHub Desktop.
React state management with RxJS

This is an example of how to use RxJS to manage state within a React app.

  • The service exposes an emitter that emits the entire state whenever a change is made.
  • The React component then calls setState() with the new state.
  • The service is passed down via props so that child components can access mutator methods.
import {Component} from 'react';
import {TodoService} from './todo.service';
export class TodoContainer extends Component {
constructor(props) {
super(props);
this.props.services.todoService = new TodoService();
this.props.state.todos = [];
}
componentDidMount() {
this.todoService.emitter.subscribe(todos => {
this.setState({this.props.state.todos: todos});
});
}
componentWillUnmount() {
this.props.services.todoService.dispose();
}
render() {
return (
<div>
<TodoList {...this.props} />
<AddTodo />
</div>
);
}
}
import {Subject} from 'rxjs/Subject';
import {ajax} from 'rxjs/observable/dom/ajax';
export class TodoService {
constructor() {
this.emitter = new Subject();
this.todos = [];
}
const getTodos = (todos) => {
ajax({url: '/todos'}).subscribe(
(data) => {
this.todos = data;
// Emit to subscribers
this.emitter.next(this.todos);
},
(error) => {
// Log the error
}
)
.retry(3);
};
const addTodo = (todo) => {
ajax({
url: '/todos',
method: 'post',
body: todo
}).subscribe(
(data) => {
this.todos = Object.assign({}, this.todos, [
...this.todos,
{
text: todo.text,
completed: todo.completed
}
]);
this.emitter.next(this.todos);
},
(error) => {
// Log the error
}
).retry(3);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment