Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using A Single Source of Truth(Data) #137

Open
Amoodaa opened this issue Oct 2, 2019 · 1 comment
Open

Using A Single Source of Truth(Data) #137

Amoodaa opened this issue Oct 2, 2019 · 1 comment
Assignees

Comments

@Amoodaa
Copy link
Collaborator

Amoodaa commented Oct 2, 2019

import React, { Component } from 'react';
import DataSource from '../../services/dataSource';

const WithSubscription = (WrappedComponent, selectData) => {
  return class extends Component {
    state = {
      data: selectData(DataSource, this.props),
    };

    componentDidMount() {
      // ... that takes care of the subscription...
      DataSource.addChangeListener(this.handleChange);
    }

    componentWillUnmount() {
      DataSource.removeChangeListener(this.handleChange);
    }

    handleChange = () =>
      this.setState({ data: selectData(DataSource, this.props) });

    render() {
      const { data, props } = this.state;
      return <WrappedComponent data={data} {...props} />;
    }
  };
};

export default WithSubscription;
  • using some kind of a handmade Data Store, with a subscription system
import api from './api';

const DataSource = {
  data: {
    loggedUser: {},
    users: [],
    channels: [],
  },
  subscribers: [],
  addChangeListener: handleChange => {
    if (DataSource.subscribers.indexOf(handleChange) === -1)
      DataSource.subscribers.push(handleChange);
  },
  removeChangeListener: handleChange => {
    DataSource.subscribers = DataSource.subscribers.filter(
      e => e !== handleChange
    );
  },
  onChange: () => DataSource.subscribers.forEach(fun => fun()),
};

export default DataSource;
@Amoodaa
Copy link
Collaborator Author

Amoodaa commented Oct 2, 2019

@11janci give us ur feedback :D
TMW IS GONNA BE EXCITING
implementing the socket and this thing in 1 day, i wonder if we can do it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant