0

I have the below fetch request in my Mobx store:

 getAllLegoParts = action("get all lego", () => {
this.legoParts = fromPromise(
  fetch("http://localhost:8000/LegoPieces", {
    method: "GET",
    cache: "no-store"
  }).then(response => response.json())
 );
 });
}

I am using this in the below ReactJS class:

class ViewLegos extends Component {
 constructor(props) {
 super(props);
 this.props.store.getAllLegoParts();
}

render() {
console.log(this.props.store.legoParts.value);
return (
  <div>
    <table>
      <thead>
        <tr>
          <th>Piece</th>
          <th>Type</th>
        </tr>
      </thead>
      <tbody>
        {this.props.store.legoParts.map(legoPart => (
          <tr key={legoPart.id}>
            <td>{legoPart.piece}</td>
            <td>{legoPart.piece}</td>
            <td>{legoPart.type}</td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);
}
}

export default inject("store")(observer(ViewLegos));

However I have two issues:

  1. Console.log prints twice - in one case in prints undefined, in the second it prints an array of objects(which is what I want).

  2. I get an error saying:

    TypeError: this.props.store.legoParts.map is not a function
    

Grateful for your help!

Nespony
  • 857
  • 3
  • 14
  • 27
  • Please post a functional example that illustrates your problem on [codesandbox](https://codesandbox.io/s/new). For more help see [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – palaѕн Dec 31 '17 at 15:43

1 Answers1

1

Is it possible to wait until the component has mounted before fetching its display data? Here is some pseudo code that might help:

class ViewLegos extends Component {

   componentDidMount() { fetchLegos() }

   render() {
     const allowRender = this.props.store.legoParts && this.props.store.legoParts.length

     if (allowRender) {  
       // display lego data
     }

     return null
   }

}

In this example, we wait for the component to mount, fetch the data, and only display it when it exists.

Looking through your code, it looks like you just need to be more defensive and handle component display when legoParts are not yet defined. They wont be defined in the beginning due to the fact your async fetch won't complete before the render.

lfender6445
  • 25,940
  • 9
  • 95
  • 82