josephT
josephT

Reputation: 842

Axios not returning data to rootSaga

so I'm learning Redux Saga and using Axios to make an API call. Even if you don't know Redux Saga, but you know Axios, you might still be able to help!

Here is the code for my rootSaga, that gets my action and calls getBlogsSaga.

import {takeEvery, call, put, select} from 'redux-saga/effects'
import {BLOGS} from '../store/actions/constants'
import {getBlogsSaga} from './getBlogsSaga'
import {setBlogs} from '../store/actions/blogActions'

function* displayBlogs() {
    const blogs = yield call(getBlogsSaga);
    console.log(yield call(getBlogsSaga))
    yield put(setBlogs(blogs))
}
//watcher saga
function* rootSaga() {
    yield takeEvery(BLOGS.LOAD, displayBlogs)
}

export default rootSaga;

Here is the axios call, which does return the data when I console.log it.

import axios from 'axios'
const API_URL = "http://localhost:3004/blogs/";

const getBlogsSaga = async () => {
    await axios
  .get(API_URL)
  .then(function (response) {
    const data = response.data;
    console.log(data)
    return data;
  })
  .catch(function (error) {
    console.log(error);
 });
}

export {getBlogsSaga}

Lastly, here is a console.log to show what I mean. The rootSaga asks for the data but never receives it even though axios successfully delivers it.

getBlogsSaga.js:11 (3) [{…}, {…}, {…}]
rootSaga.js:8 undefined

Upvotes: 1

Views: 290

Answers (1)

keysl
keysl

Reputation: 2167

saga's call is actually can handle promises just fine, so making your axios code like this should work fine. no need to make it await in here, you can do the heavy lifting of waiting in the generator

import axios from 'axios'
const API_URL = "http://localhost:3004/blogs/";

const getBlogsSaga = () => {
  return axios
  .get(API_URL)
  .then(function (response) {
    const data = response.data;
    console.log(data)
    return data;
  })
  .catch(function (error) {
    console.log(error);
 });
}

export {getBlogsSaga}

I made a simple poc here :) https://jsfiddle.net/vqoktfwd/1/

Upvotes: 2

Related Questions