如何使用redux saga将返回的获取数据传递给reducer

问题描述 投票:0回答:2

我正在执行获取请求,该请求在数据库中产生了一个新用户。所有这些都起作用,并且使新用户/返回了api-key。

问题是我无法将收到的获取请求响应传递给我的reduces。我想知道是否应该调用另一个操作作为对成功获取请求的响应,该请求触发了reducer并将请求的响应作为有效负载。

或者如果我能够立即将获取请求的响应传递给reducer。这是我的SAGA:

import { call, put, takeEvery, takeLatest, delay } from 'redux-saga/effects';
import {REGISTER} from '../redux/actions/loginAPIcall'

function* callAPIregister(){ 
    const json = yield fetch('http://spotlight-api.local/api/register', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
         'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: 'apptest3',
          email: '[email protected]',
          password: '123456789'
        }),
      })
      .then((response) => response.json())
              .then(data => {
                  console.log(data)
              })
    yield put({type: 'REGISTER_SAGA', payload: json})
}

export function* watchAPIcall(){
    yield takeEvery(REGISTER, callAPIregister)
}

下面是我的减速器:

import {REGISTER, LOGIN} from '../actions/loginAPIcall'

const initialState = {
    apiCalling: false, 
    occupation: null
}

function addAPIcall(state = initialState, action, payload){
    console.log('inside the api reducer')
    switch(action.type){
        case "REGISTER_SAGA":
            console.log('inside register_saga reducer', payload)
            return {
                apiCalling: true,
                occupation: 'REGISTER'
                }
        case LOGIN:
            return {
                apiCalling: true,
                occupation: 'LOGIN'
            }
        default:
            return state;
            }
}
export default addAPIcall

登录时,reducer有效负载现在未定义。

reactjs react-native redux redux-saga
2个回答
1
投票
如果从产生的语句中返回Promise,则

yield本身将等待直到Promise被解决。因此正确的callAPIregister将是

function* callAPIregister(){ 
    // yield will wait for Promise to resolve
    const response = yield fetch('http://spotlight-api.local/api/register', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
         'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: 'apptest3',
          email: '[email protected]',
          password: '123456789'
        }),
      })
    // Again yield will wait for Promise to resolve
    const data = yield response.json()
    console.log(data)
    yield put({type: 'REGISTER_SAGA', payload: data})
}

而且我建议在using call语句中考虑call。它使单元测试更容易


0
投票

我认为,这件事对您有用。如果在读取时出现任何错误,则使“ FETCH_FAILED”类型正确,然后即可捕获该错误。因此,在化简器的initial_state对象中再添加一个变量。

sagas.js

yield

在化简器中,您可以在初始状态对象中创建一个变量,然后在您的'REGISTER_SAGA'中捕获我们从传奇获得的数据

reducer.js

import { call, put, takeLatest, takeEvery } from 'redux-saga/effects';
import {REGISTER} from '../redux/actions/loginAPIcall';

function getData(payload){
    return fetch('http://spotlight-api.local/api/register', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
    })
    .then(response => response.json())
    .then(json => json)
    .catch(error => {
      throw error;
    });
}

function* callAPIregister(){ 
  try{
    const payload = {
      name: 'apptest3',
      email: '[email protected]',
      password: '123456789'
    }
    const response = yield call(getData, payload);

    //In this please check what is the name of your data variable
    //Eg if its message then you can
    console.log(response);
    //use response: response.message
    yield put({type: 'REGISTER_SAGA', response: response})
  } catch (error){
    yield put({ type: 'FETCH_FAILED', error });
  }
}

export function* watchAPIcall(){
    yield takeEvery(REGISTER, callAPIregister)
}
© www.soinside.com 2019 - 2024. All rights reserved.