The problem with the fetch request in MobX and React

57 Views Asked by At

I'm trying to download data from the server and output it to the console for verification, but for some reason undefined is output

MobX:

import { makeAutoObservable } from "mobx"

class Data {
    users
    constructor() {
        makeAutoObservable(this)
    }

    async fetchUsers() {
        try {
          const response = await fetch('https://dummyjson.com/users');
          const data = await response.json();
          this.users = data;
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      }
}
const data = new Data()
export default data

React:

import { observer } from 'mobx-react-lite';
import React from 'react'
import { useEffect } from "react";
import data from '../store/data.js'

const MyTable = observer( () => {

    useEffect(() => {
        data.fetchUsers()
      }, [])
    console.log(data.users)

    return ( 
        <div></div>
     );
})

export default MyTable;

I output a data object to the console, it seems to have data in it, or I don't understand something.

1

There are 1 best solutions below

0
domehead100 On

fetchUsers is an async function. Your console.log is running before the users are fetched.

Add an "await" in front of data.fetchUsers and put the console log inside of the useEffect, or treat fetchUsers like a promise and put the console.log inside of a ".then" continuation.

Either way you should see your uses in the console every time the users are fetched.