Arturio
Arturio

Reputation: 466

How to use Redux Sagas to load single object?

I've been working on a react project, using redux and sagas. So far I was able to create a structure where my component would dispatch an action requesting a list, then sagas takes this action and calls a function that would make the request to the backend. I then store this list on redux, and my component reads the list from redux.

Now I need to load a single object from backend. I thought about not using sagas for that request, but I guess it makes sense to make this request using sagas and storing this single object on redux.

I can't figure how to make the rootSaga function accept to take my function with 'id' as parameter.

To ilustrate the scenario, here is some code:

this is the root saga function, it would make the API request and call the action to store on redux

export function* loadEvent({ id: number }) {
  try {
    console.log('load single event');

    yield put(loadEventSuccess(event));
  } catch (err) {
    yield put(loadFailure());
  }
}

This is the rootSaga function that is supposed to get the action I dispatched and trigger my saga function. The problems is that it does not accept me to call the function with a parameter. Even if I could, I don't know how to pass a parameter to it.

export default function* rootSaga() {
  return yield all([
    takeLatest(EventsTypes.LOAD_EVENT_REQUEST, loadEvent),
  ]);
}

Of course, before all that there is an action I dispatched from my function component.

Another thing that has been confusing me is if the approach I've been using is ok. I could make this request from my function component and store the data in its state. By doing that I wouldn't involve redux nor sagas. Would that make sense?

Upvotes: 0

Views: 935

Answers (1)

antonio mesquita
antonio mesquita

Reputation: 71

Your approach is completely right as you should try to make every api call throw your sagas, but you just made a small mistake

function* loadEvent({ payload }) {
const { id } = payload;
  try {
    const response = yield call(api.get, `localhost:4000/api/${id}`);
    yield put(loadEventSuccess(event));
  } catch (err) {
    yield put(loadFailure());
  }
};

You also don't need to export the generator functions, and in my example I'm simulating an api get call using axios. And don't forget to import { call } from "redux-saga/effects";

Upvotes: 2

Related Questions