Answer a question

Working with React-admin I want add a background task. Every 30 seconds or so, I want to check my API if there any new orders. If managed to set this up trough sagas. The downside is, I want it to run only after login, and only for a certain user type. I don't know how to access any authorization inside the saga and can't find anything about it in the docs or online. And on logout I want to cancel the interval.

Here is my saga so far:

import {call, put, takeEvery} from "redux-saga/effects";
import {eventChannel} from "redux-saga";
import {showNotification} from 'react-admin';

const countdown = () => {
    return eventChannel(emitter => {
            const iv = setInterval(() => {
                const req = new Request(`http://my.api.url/orders`, {
                    method: 'GET',
                    headers: new Headers(
                        {
                            'Accept': 'application/json',
                            'Authorization': `Bearer nice_token`,
                        }
                    ),
                });
                fetch(req)
                    .then((response) => {
                        if (response.status < 200 || response.status >= 300) {
                            throw new Error(response.statusText);
                        }
                        return response.json();
                    })
                    .then((response) => {
                        emitter(response)
                    })
                    .catch(error => {
                        console.log(error);
                        // emitter(END)
                    });
            }, 30000);
            // The subscriber must return an unsubscribe function
            return () => {
                clearInterval(iv)
            }
        }
    )
}

export default function* newOrders() {
    const channel = yield call(countdown);
    yield takeEvery(channel, function* (response) {
        if (response.data.length) {
            yield put(showNotification('New order received'))
        }
    });
}

Answers

Redux action declared in react-admin: USER_LOGIN, USER_LOGIN_SUCCESS, USER_LOGOUT. Check that you have them, if not, you can use instead of them: REGISTER_RESOURCE, UNREGISTER_RESOURCE:

import {
    USER_LOGIN,
    USER_LOGIN_SUCCESS,
    USER_LOGOUT,
    REGISTER_RESOURCE,
    UNREGISTER_RESOURCE,
} from 'ra-core' 

const startStopSaga = () => function* () {
  while (true) {
    yield take(USER_LOGIN_SUCCESS) // or REGISTER_RESOURCE    

    let current_user = localStorage.getItem('current_user') // Manual rights check    
    if (!current_user.rights) {
      continue    
    }

    yield race({
      task: call(newOrders),
      cancel: take(USER_LOGOUT), // or UNREGISTER_RESOURCE   
    })
  }
}
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐