How to get data from server with mobx using functional component

177 views Asked by At

I need to make a simple GET request with mobx using functional components using fetch to server with this API https://jservice.io/api/category?id=150 Get data and then display it in my user interface component.

I spent several hours looking for a similar example but couldn't find it, please if you have a similar example or if you could demonstrate online editors how it works I would really appreciate it.

1

There are 1 answers

0
Tholle On

You could create a local component observable with useLocalObservable, and use a useEffect to fetch the data when the component is mounted and put that in the observable, and then finally render it.

Example

const { observer, useLocalObservable } = mobxReactLite;
const { useEffect } = React;

const App = observer(function App() {
  const store = useLocalObservable(() => ({
    category: null,
    setCategory(category) {
      store.category = category;
    }
  }));

  useEffect(() => {
    fetch("https://jservice.io/api/category?id=150")
      .then((res) => res.json())
      .then((res) => store.setCategory(res));
  }, []);

  if (store.category === null) return null;

  return (
    <div>
      <div>{store.category.title}</div>
      {store.category.clues.map((clue) => (
        <div key={clue.id}>{clue.question}</div>
      ))}
    </div>
  );
});

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mobx.umd.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mobxreactlite.umd.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mobxreact.umd.production.min.js"></script>

<div id="root"></div>