How to push the json to the array state of Mobx in react

问题: I am using mobx in React now with firebase. First, there is a 'projectState' as a empty array. Second, after get the data from firestore, it is pushed into the state of Mob...

问题:

I am using mobx in React now with firebase.
First, there is a 'projectState' as a empty array.
Second, after get the data from firestore, it is pushed into the state of Mobx.
This is a code of mine.

 @observable projectState = {
    projects: []
  };

  projectGet = () => {
    firebase
      .firestore()
      .collection("projects")
      .doc("DkBFcdAOAWWl8Az")
      .get()
      .then(done => {
        const projectsTotal = JSON.stringify(done.data());
        this.projectState.projects.push(projectsTotal);

      });
  };

'done.data()' gives the json type file like below.

{"id": "3", "title": "good"}

However, when I use 'console.log' to check the state after pushing data.
it gives me like below.

   Proxy {0: "{"content":"asdf","id":"123","title":"yoman"}", 
1: "{"content":"asdf","id":"123","title":"yoman"}",
 Symbol(mobx administration): ObservableArrayAdministration}

How can I push the json data well into the mobx state?


回答1:

You are converting the returned object into a string when you const projectsTotal = JSON.stringify(done.data());

You can change it to only assign the data.

 @observable projectState = {
    projects: []
  };

  projectGet = () => {
    firebase
      .firestore()
      .collection("projects")
      .doc("DkBFcdAOAWWl8Az")
      .get()
      .then(done => {
        this.projectState.projects.push(done.data());
      });
  };

In addition, from the stringified values, I see that Firebase returns an object literal, you probably what to convert it into an array and push each item separately.

You can use Object.values to get an array of values.

@observable projectState = {
    projects: []
  };

  projectGet = () => {
    firebase
      .firestore()
      .collection("projects")
      .doc("DkBFcdAOAWWl8Az")
      .get()
      .then(done => {
        Object.values(done.data())
              .forEach((value) => {this.projectState.projects.push(value)});
      });
  };
  • 发表于 2019-07-07 04:52
  • 阅读 ( 270 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除