Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

api.fetch saga

import { takeLatest, call, put } from 'redux-saga/effects';

// watcher saga: watches for actions dispatched to the store, starts worker saga
export function* watcherSaga() {
    yield takeLatest('FETCH_CUSTOMERS', workerSaga);
}

// worker saga: makes the api call when watcher saga sees the action
function* workerSaga() {
    try {
        const response = yield call(fetch, 'https://mydomain/api/customers');
        const customers = response.data.customers;

        // dispatch a success action to the store with the customers
        yield put({ type: 'CUSTOMERS_FETCHED', customers });
    } catch (error) {
        // dispatch a failure action to the store with the error
        yield put({ type: 'CUSTOMERS_FETCH_ERROR', error });
    }
}
Comment

redux saga fetch api

//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)
Comment

PREVIOUS NEXT
Code Example
Javascript :: update query in mongoose 
Javascript :: mongoose update subdocument by id 
Javascript :: You provided a `value` prop to a form field without an `onChange` handler 
Javascript :: javascript array loop 
Javascript :: how to make a alert popup message in javascript 
Javascript :: full month name using moment 
Javascript :: use react awesome slider in react js 
Javascript :: how to check if json data is received in ajax response 
Javascript :: javascript find and update element from array 
Javascript :: making axios call with headers 
Javascript :: how to remove last element from array in javascript 
Javascript :: angular subscribe on value change 
Javascript :: repeat string in javascript 
Javascript :: Javascript object convert into JSON 
Javascript :: reference of event listener funtion to remove 
Javascript :: convert js date to utc 
Javascript :: initalise typed js library 
Javascript :: module.exports multiple functions 
Javascript :: javascript charcode 
Javascript :: date format in moment js 
Javascript :: javaScript setFullYear() Method 
Javascript :: how to check if local storage is available 
Javascript :: how to connect react to backend 
Javascript :: what is jquery used for 
Javascript :: modulus js 
Javascript :: js outputting data 
Javascript :: react video 
Javascript :: blur js 
Javascript :: laravel vue global function 
Javascript :: jquery get value of element 
ADD CONTENT
Topic
Content
Source link
Name
5+7 =