简体   繁体   中英

How to use yield inside the taskmanager callback react native

I want to use yield inside the TaskManager.defineTask callback and dispatch redux store with yield but i cant do it

I've tried everything

import { all, put, call } from 'redux-saga/effects'
import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';

function* dispatchLocation(locations){
    console.log("Entro d")
    yield put({ type: 'permission/SET_LOCATION', data: locations })
}

TaskManager.defineTask('LocationWatcher', ({ data: { locations }, error }) => {
    if (error) {
        // check `error.message` for more details.
        return;
    }
    console.log('enn')
    yield dispatchLocation(locations)
});

function* watchLocation(){
    let { status } = yield Permissions.getAsync(Permissions.LOCATION);
    console.log(status)
    if (status === 'granted') {
        Location.startLocationUpdatesAsync('LocationWatcher',{})
    }
}

export default function* rootSaga() {
    //call(watchLocation())
    yield all([
        watchLocation()
    ])
}

In javascript if you want to use yield you need to do so from a generator function, so you would have to rewrite your LocationWatcher callback to be a generator function like

TaskManager.defineTask('LocationWatcher', function* ({ data: { locations }, error }) {
    ...
});

That said this won't accomplish what you're looking for here - redux-saga can only dispatch yielded actions from within a saga which the LocationWatcher callback is not. I think the better path for you here is to import your redux store and dispatch your action directly from within your task. So something like:

import store from './path/to/redux/store';
TaskManager.defineTask('LocationWatcher', ({ data: { locations }, error }) => {
    if (error) {
        // check `error.message` for more details.
        return;
    }
    console.log('enn')
    store.dispatch({ type: 'permission/SET_LOCATION', data: locations })
});

and do away with the dispatchLocation generator altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM