Best practice to fetch sync

124 views Asked by At

Im trying to get the model User which have a relation with Projects. Here is my models/user.js

 *fetchUser({ payload, callback }, { call, put }) {
      const user = yield call(queryUser, payload);
      yield put({
        type: 'setCurrentUser',
        payload: user,
      });
      if (callback) callback();
    },

What is the best practice? Where should I call the function queryProjects? Maybe below this line?

const user = yield call(queryUser, payload);
const projects = yield call(queryProjects, user); // new api call
1

There are 1 answers

0
Sisir On

First Approach

Make two models, users & projects

Then you can do this

*fetchUser({ payload, callback }, { call, put }) {
      const user = yield call(queryUser, payload);
      yield put({
        type: 'setCurrentUser',
        payload: user,
      });
      yield put({type: 'projects/fetchByUserId', payload: user.id});
    },

Inside your `projects` model.

*fetchByUserId({payload){
    // do ajax call
}

Once you have data for projects you can filter the project array with user id (considering your project has something like project.user_id) and show them into the app.

Second Approach

You can have your backend server send the project list for user in the user object.

{
    id: 1,
    username: "foo",
    projects: [
        {id: 1},
        {id: 2}
        {id: 3}
    ]
}

I hope it makes sense.