redux saga fetch json

//EXAMPLE FETCH DATA API REDUX SAGA

// USER ACTION CREATOR
export const REQUEST_API_DATA = 'REQUEST_API_DATA'
export const RECEIVE_API_DATA = 'RECEIVE_API_DATA'

export const requestApiData = () => ({ type: REQUEST_API_DATA })

// USER REDUCER
import { REQUEST_API_DATA, RECEIVE_API_DATA } from '../actions/user'

export default (state = {}, { type, payload }) => {
  switch (type) {
    case RECEIVE_API_DATA:
      return payload.users
    default:
      return state
  }
}

// USER SAGA
import axios from 'axios'
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import { REQUEST_API_DATA, RECEIVE_API_DATA } from './actions/user'

function* userReceiveAll(action) {
  try {
    const { data } = yield call(axios.get, 'https://jsonplaceholder.typicode.com/users')
    yield put({ type: RECEIVE_API_DATA, payload: { users: data } })
  } catch (e) {
    console.log(e.message)
  }
}
export default function* userSendAll() {
  yield takeLatest(REQUEST_API_DATA, getApiData)
}

// REDUX STORE
import { createStore, applyMiddleware, combineReducer } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { all } from 'redux-saga/effects'
import logger from 'redux-logger'
import userReducer from './reducers/user'
import userSaga from './sagas/user'

function* saga() {
  yield all([userSaga()]) 
}

export const store = () => {
 const sagaMiddleware = createSagaMiddleware()
 const store = createStore(combineReducer({users: userReducer}), 
 applyMiddleware(sagaMiddleware, logger)) 
 sagaMiddleware.run(saga)
 return store;
}

// USER COMPONENT
import React from 'react'
import { connect } from 'react-redux'
import { requestApiData } from './actions'

class User extends React.Component {
  componentDidMount() {
    this.props.fetchAll()
  }
  render() {
    const { users } = this.props.state
    const results = users.length > 0 ? users : []
    return (
      <div>
        {results.map((v) => (
          <ul key={v.id}>
            <li>{v.username}</li>
          </ul>
        ))}
      </div>
    )
  }
}

const mapStateToProps = (state) => ({ state })
const mapDispatchToProps = (dispatch) => ({ fetchAll: () => dispatch(requestApiData()) })

export default connect(mapStateToProps, mapDispatchToProps)(User)

3.8
5
Flexo 85 points

                                    // USER ACTION CREATOR
export const userState = {};
export const RECEIVED_ALL = &quot;RECEIVED_ALL&quot;;
export const REQUEST_ALL = &quot;REQUEST_ALL&quot;;

export const userRequestAllActionCreator = (type) =&gt; ({
  type: type
});


// USER REDUCER
import { userState, RECEIVED_ALL } from &quot;../actions/user&quot;;

export const userReducer = (state = userState, action) =&gt; {
  switch (action.type) {
    case RECEIVED_ALL:
      return action.payload;
    default:
      return state;
  }
};

// USER SAGA
import axios from &quot;axios&quot;;
import { put, takeLatest } from &quot;redux-saga/effects&quot;;
import { REQUEST_ALL, RECEIVED_ALL } from &quot;../actions/user&quot;;

function* userReceiveAll() {
  const { data } = yield axios.get(&quot;https://jsonplaceholder.typicode.com/users&quot;);
  yield put({ type: RECEIVED_ALL, payload: data });
}

export function* userSagaAll() {
  yield takeLatest(REQUEST_ALL, userReceiveAll);
}

3.8 (5 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source