I am new to mobx and trying to create a simple project that displays a list of NBA players' info using mobx-state-tree.
The fetchPlayers() method in useEffect successfully gets the information and but never triggered a re-render. Is it possible that I use observer in a wrong way?
App.js
import { useEffect } from "react";
import { createList } from "./mst/createList";
import { observer } from "mobx-react-lite";
import { values } from "mobx"
function App() {
const playerListStore = createList();
useEffect(() => {
playerListStore.fetchPlayers();
}, [playerListStore]);
console.log(playerListStore.players);
return (
<div className="App">
<h1>NBA Players</h1>
<ul>
{values(playerListStore.players).map((player, index) => (
<li key={index}>
<p>{player.firstName}</p>
</li>
))}
</ul>
</div>
)
}
export default observer(App);
store.js
import { types } from "mobx-state-tree"
const URL = "https://www.balldontlie.io/api/v1/players"
const fetchData = async () => {
const response = await fetch(URL);
return response.json();
}
const PlayerModel = types.model("PlayerModel", {
firstName: types.optional(types.string, "null"),
lastName: types.optional(types.string, "null"),
position: types.optional(types.string, "null"),
team: types.optional(types.string, "null")
});
export const PlayerListModel = types.model("PlayerListModel", {
players: types.array(PlayerModel)
})
.actions(self => ({
setPlayers(newPlayers) {
self.players = newPlayers
},
async fetchPlayers() {
const data = await fetchData();
const newPlayers = data.data.map((player) => ({
firstName: player.first_name,
lastName: player.last_name,
position: player.position,
team: player.team.name
}));
self.setPlayers(newPlayers);
}
}));
Any help will be appreciated.