0

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."})
      }
    }
BarakOren
  • 99
  • 1
  • 8
  • show please how did you use select? – Oro Nov 08 '21 at 15:17
  • @RamanNikitsenka i tried in a few ways as i seen in some examples.. it didnt work, probably im doing it wrong. ill add it now – BarakOren Nov 08 '21 at 15:18
  • 1
    Does this answer your question? [redux saga selectors, how do I access state from a saga?](https://stackoverflow.com/questions/43475888/redux-saga-selectors-how-do-i-access-state-from-a-saga) – Mark Rotteveel Nov 09 '21 at 11:06

2 Answers2

2

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);
  }
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

By the way, you could also get a field in your redux state
Let's say your redux state looks like this

{ key1: val1 , key2:{}}

You could const key1 = yield select(state => state.key1).
Since normally you would not want to select the whole redux state

hansss
  • 321
  • 4
  • 4