virtualitems / javascript-toolkit

My javascript toolkit
1 stars 0 forks source link

mvvm with reactjs #13

Open deltecacarrasco opened 7 months ago

deltecacarrasco commented 7 months ago
// Model
const initialData = {
  counter: 0
};

// ViewModel
const useCounterViewModel = () => {
  const [data, setData] = useState(initialData);

  const incrementCounter = () => {
    setData(prevData => ({
      ...prevData,
      counter: prevData.counter + 1
    }));
  };

  return { data, incrementCounter };
};

// View
const CounterView = ({ counter, onIncrement }) => {
  return (
    <div>
      <p>Counter: {counter}</p>
      <button onClick={onIncrement}>Increment</button>
    </div>
  );
};

const App = () => {
  const { data, incrementCounter } = useCounterViewModel();

  return <CounterView counter={data.counter} onIncrement={incrementCounter} />;
};

ReactDOM.render(<App />, document.getElementById('root'));
deltecacarrasco commented 7 months ago
// Model.js
// This is the data source of the application
class Model {
  constructor() {
    this.count = 0; // initial value
  }

  increment() {
    this.count++; // increase the count by one
  }

  decrement() {
    this.count--; // decrease the count by one
  }
}

// ViewModel.js
// This is the business logic of the application
import { makeAutoObservable } from "mobx"; // a library for state management

class ViewModel {
  constructor(model) {
    this.model = model; // inject the model as a dependency
    makeAutoObservable(this); // make the view model observable by MobX
  }

  get count() {
    return this.model.count; // return the current count from the model
  }

  increment() {
    this.model.increment(); // call the increment method on the model
  }

  decrement() {
    this.model.decrement(); // call the decrement method on the model
  }
}

// View.js
// This is the UI logic of the application
import React from "react"; // import React library
import { observer } from "mobx-react"; // a library for connecting React and MobX

// This is a functional component that takes a view model as a prop
const View = observer(({ viewModel }) => {
  // Use the view model to display and update the UI
  return (
    <div>
      <h1>Counter</h1>
      <p>The current count is {viewModel.count}</p>
      <button onClick={() => viewModel.increment()}>+</button>
      <button onClick={() => viewModel.decrement()}>-</button>
    </div>
  );
});

// App.js
// This is the entry point of the application
import React from "react";
import ReactDOM from "react-dom";
import Model from "./Model";
import ViewModel from "./ViewModel";
import View from "./View";

// Create a model instance
const model = new Model();

// Create a view model instance with the model
const viewModel = new ViewModel(model);

// Render the view component with the view model
ReactDOM.render(<View viewModel={viewModel} />, document.getElementById("root"));