1
votes

I'm doing a fetch call from an API, turning that into json, then getting a object(with nested object arrays). I can log this in the console no problem.

The problem is that I'm doing this for a school project and the instructor specifically wants us to manage state in a model using mobx living in a js file that we pass down. I cannot get any data into model.

Using a literal initialization, I can get the arrays to show up in my console from app with a consolelog, but the arrays are always empty.

Really stumped on why the object arrays aren't accepting any values

I cannot pass any data into the observable. I've tried just assigning the whole thing to the response, assigning matching parts, pushing, concating, Object.assign, doing a deep copy. I've also tried mapping the values from the response object into the appropriate arrays.

//need fetch response in here
let model = observable({
  Ratings: [],
  Instructors: [],
  Likes: [],
  Schools: []
});

export let Model = toJS(model);

Model.Fetch = async function() {
  const endPoint = "http://s28.ca/sodv2201/instructor/ratings";
  const req = {};

  let P = await fetch(endPoint, {
    method: "POST",
    body: JSON.stringify(req)
  });
  let data = await P.json();

  //the object I need(goes deeper, ex. data.Ratings.Ratings,
  //data.Ratings.Instructors)
  let ratings = data.Ratings;
  //doesn't work
  model.Ratings = ratings.Ratings;

  //model appears to be right, but fails when
  //adding to Model, can see arrays, no data in them
  model = ratings;
  console.log(model);

No error messages, just can't fetch data into observable object array.

1
Have checked whether you are getting data from the API or whether the variable P contains the properties you want? - Ahmad Faiyaz

1 Answers

0
votes

When you call toJS(model) you are returning plain JS object. Model is not going to be observable.

toJS - Recursively converts an (observable) object to a javascript structure.

MobX Docs