Flux Pattern In React Js With Example
Sumit Mishra
Php Architect || Technical Strategist || IT Consultant || Help You In Building IT Team || Project Outsourcing
Install Dependencies: You'll need to install flux package. You can install it using npm or yarn:
npm install flux
or
yarn add flux
Implement Flux Components:
actions.js
import Dispatcher from './dispatcher';
export const ActionTypes = {
ADD_TODO: 'ADD_TODO',
REMOVE_TODO: 'REMOVE_TODO',
};
export const ActionCreators = {
addTodo: (text) => {
Dispatcher.dispatch({
type: ActionTypes.ADD_TODO,
payload: text,
});
},
removeTodo: (index) => {
Dispatcher.dispatch({
type: ActionTypes.REMOVE_TODO,
payload: index,
});
},
};
dispatcher.js
领英推荐
import { Dispatcher } from 'flux';
export default new Dispatcher();
store.js
import { EventEmitter } from 'events';
import Dispatcher from './dispatcher';
import { ActionTypes } from './actions';
class TodoStore extends EventEmitter {
constructor() {
super();
this.todos = [];
}
getAll() {
return this.todos;
}
handleActions(action) {
switch (action.type) {
case ActionTypes.ADD_TODO:
this.todos.push({
text: action.payload,
completed: false,
});
this.emit('change');
break;
case ActionTypes.REMOVE_TODO:
this.todos.splice(action.payload, 1);
this.emit('change');
break;
default:
// Do nothing
}
}
}
const todoStore = new TodoStore();
Dispatcher.register(todoStore.handleActions.bind(todoStore));
export default todoStore;
App.js (React Component)
import React, { useState, useEffect } from 'react';
import { ActionCreators } from './actions';
import TodoStore from './store';
const TodoApp = () => {
const [todos, setTodos] = useState(TodoStore.getAll());
useEffect(() => {
TodoStore.on('change', updateTodos);
return () => {
TodoStore.removeListener('change', updateTodos);
};
}, []);
const updateTodos = () => {
setTodos(TodoStore.getAll());
};
const handleAddTodo = () => {
const text = prompt('Enter a new todo:');
if (text) {
ActionCreators.addTodo(text);
}
};
const handleRemoveTodo = (index) => {
ActionCreators.removeTodo(index);
};
return (
<div>
<button onClick={handleAddTodo}>Add Todo</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo.text}
<button onClick={() => handleRemoveTodo(index)}>Remove</button>
</li>
))}
</ul>
</div>
);
};
export default TodoApp;
Usage in index.js (or your main entry file):
import React from 'react';
import ReactDOM from 'react-dom';
import TodoApp from './App';
ReactDOM.render(<TodoApp />, document.getElementById('root'));
This example creates a simple todo list application where you can add and remove items. The Flux pattern is used to manage the application state through actions, a dispatcher, and a store. The React component (TodoApp) listens for changes in the store and updates accordingly.
Remember to include this basic structure into your own project and adjust it as needed based on your application's requirements.