0
votes

I am creating a simple React single page app, that is pulling info from Behance API, and showing it on the site.

I am using MobX to store portfolio items, as well as modules a from a single item.

The store.js looks like:

import { observable } from 'mobx';

class Store {
  constructor() {
    this.storeState = observable({
      portfolioItems: [],
      singleItem: {},
    });
  }
}

export default new Store();

And my Single.js looks like this

import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { action, toJS } from 'mobx';
import { css } from 'emotion';

import { getItem } from '../../services/api';
import { errorHandler } from '../../services/errorHandler';
import { isInObservableObject } from '../../helpers/isObservable';
import store from '../../state/store';

import Image from '../../components/Image/Image';
import Text from '../../components/Text/Text';

const singleContainer = css`
  display: block;
`;

const backButton = css`
  display: block;
  padding: 20px;
  position: fixed;
  bottom: 50px;
  right: 30px;
  border: 0;
  font-size: 16px;
  cursor: pointer;
  text-transform: uppercase;
  color: #FFFFFF;
  background-color: rgba(0, 0, 0, 0.5);
`;

@observer
class Single extends Component {
  static moduleHandler(module) {
    return (module.sizes) ?
      (
        <Image
          alt="Module image"
          key={module.id}
          src={module.sizes.original}
        />
      ) :
      (
        <Text
          key={module.id}
          type="tertiary"
        >
          {module.text_plain}
        </Text>
      );
  }

  componentWillMount() {
    const {match} = this.props;

    const itemId = match.params.id;

    if (!isInObservableObject(store.storeState.singleItem, itemId)) {
      getItem(itemId).then((result) => {
        if (typeof result.errors !== 'undefined') {
          store.storeState.singleMessage = errorHandler(result.errors);
          return;
        }

        store.storeState.singleItem[itemId] = result.project.modules;
      }).catch((error) => {
        const errorMessage = `Error: ${error}`;
        store.storeState.singleMessage = errorMessage;
      });
    }
  }

  @action.bound handleBack() {
    const {history} = this.props;
    history.goBack();
  }

  render() {
    const { singleItem } = store.storeState;
    const { match } = this.props;

    const itemId = match.params.id;

    const storeObject = toJS(singleItem);
    const iterableItem = storeObject[itemId];

    return (
      <div className={singleContainer}>
        {
          iterableItem.map((module) => (
            this.constructor.moduleHandler(module)
          ))
        }
        <button
          className={backButton}
          onClick={this.handleBack}
        >
          Go Back
        </button>
      </div>
    );
  }
}

export default Single;

I'm using php to bypass issues with CORS, so my api.js which is used for fetching info looks like this:

const fetchData = async (endpoint, method, headers, body) => {
  const options = {};

  options.method = method;
  options.headers = headers || {};

  if (typeof body !== 'undefined') {
    options.body = JSON.stringify(body);
  }

  const url = `http://localhost/server.php?project=${endpoint}`;

  return fetch(url, options).then((response) => response.json());
};

export function getItems() {
  const headers = {
    Accept: 'application/json;charset=utf-8',
    'Content-Type': 'application/json;charset=utf-8',
  };

  return fetchData('', 'GET', headers);
}

export function getItem(id) {
  const headers = {
    Accept: 'application/json;charset=utf-8',
    'Content-Type': 'application/json;charset=utf-8',
  };

  return fetchData(id, 'GET', headers);
}

The problem I'm facing is: how do I get the data out of the store? With portfolio items, it's easy, since those are stored in an array, and I can just map them.

But the problem is that in the singleItem object, I'm storing modules of each project, and it stores it as an observable object {$mobx: ObservableObjectAdministration}, which I can console.log out and I can see that for the project I got the correct modules

62973499: (17) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

But I cannot get those modules out. I tried with

singleItem[itemId]
singleItem.itemId
toJS(singleItem)[itemId] // toJS should convert the observable object to regular one
toJS(singleItem).itemId

nothing worked.

I'm storing them in this way because I have 20 or so projects, so each should be recognizable (they have a unique ID which I'm using as a key).

1

1 Answers

0
votes

To answer my own question, since I found the way to fix this.

First I changed the store - my singleItem is now a Map

import { observable } from 'mobx';

class Store {
  constructor() {
    this.storeState = observable({
      portfolioItems: [],
      singleItem: new Map(),
    });
  }
}

export default new Store();

Next, I changed my componentWillMount to

  componentWillMount() {
    const {match} = this.props;

    const itemId = match.params.id;

    if (!isInObservableObject(store.storeState.singleItem, itemId)) {
      getItem(itemId).then((result) => {
        if (typeof result.errors !== 'undefined') {
          store.storeState.singleMessage = errorHandler(result.errors);
          return;
        }

        store.storeState.singleItem.set(itemId, result.project.modules);
      }).catch((error) => {
        const errorMessage = `Error: ${error}`;
        store.storeState.singleMessage = errorMessage;
      });
    }
  }

Then I stumbled upon this

Why componentWillMount is called after rendering?

And I used that to my advantage:

render() {
    const { singleItem } = store.storeState;
    const { match } = this.props;

    const itemId = match.params.id;

    return (
      <div className={singleContainer}>
        {
          !singleItem.get(itemId) ? (
            <Loader />
          ) : (
            singleItem.get(itemId).map((module) => (
              this.constructor.moduleHandler(module)
            ))
          )}
        <button
          className={backButton}
          onClick={this.handleBack}
        >
          Go Back
        </button>
      </div>
    );
  }

So if nothing is fetched I am showing my loader, and when it finishes, I am showing the item.

Works :D