Home > Blockchain >  how to get redux state inside saga file
how to get redux state inside saga file

Time:11-09

i need to get a state from redux, to use it on API call inside the saga file.
i checked about the select API. but its a problem here.
i want to use one function just for the API call. to run this function i need to get the current state from redux. and than put it inside the generator function, i didnt succeed to use the select.

    async function getApi(){
// GET THE STATE IN THE NEXT LINE
        try{
            const callByCity = await fetch(`https://www.test.com/APICALL${REDUX STATE}...
`)
            const result= await callByCity.json()
            return result
        } catch(error) {
            console.log(error.message)
        }
    }
    
    function* fetchMainCity(action){
      try{
        const mainCity = yield call(getApi);
        yield put({ type: "GET_CITY_SUCCESS", result: result})
      } catch (e) {
        yield put({type: "GET_CITY_FAILED", message: "Sorry, We Have A Problem."})
      }
    }

CodePudding user response:

You've got a mix of a saga and an async function. You can get the state while inside the saga. You can't get it in the async function. So if you want to keep getApi as an async function, you will need to get the state first, and then pass it in:

function* fetchMainCity(action) {
  try {
    const state = yield select();
    const mainCity = yield call(getApi, state);
    //...etc
}

async function getApi(state) {
  // do stuff with the state
}

Alternatively, if you change getApi to be a saga, then it can select from the state itself:

function* getApi() {
  try {
    const state = yield select();
    const callByCity = yield fetch(`https://www.test.com/APICALL${/* state stuff */}`);
    const result = yield callByCity.json();
    return result;
  } catch (error) {
    console.log(error.message);
  }
}

CodePudding user response:

if you run into this problem, use this:
redux saga selectors, how do I access state from a saga?
and also use @NicholasTower answer.
and what got me stuck in my question, is how to add a parameter to my getApi function. the answer for this is const mainCity = yield call(getApi, state); instad of the normal yield call(getApi(state))

  • Related