How to run redux-saga middleware on the any dispatch action? - javascript

I have defined following redux saga middleware function in 'usersaga.js'
import {call, put, takeEvery, takeLatest} from "redux-saga/effects";
import {REQUEST_API_DATA, receiveApiData} from '../store/actions';
import userServiceObject from '../services/user.service';
// Worker Saga function will be fired on USER_FETCH_ACTIONS
export function* getApiData(action){
console.log(action)
try{
// Do Api Call
const data = yield call(userServiceObject.getUsers);
console.log(data.data);
yield put(receiveApiData(data.data));
}
catch(error){
console.log("this is error part and executing");
console.log(error);
}
}
In the 'index.js' file I use "run" method to run above function getApiData
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, combineReducers, applyMiddleware } from 'redux';
import {Provider} from 'react-redux';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import contactReducer from './store/reducers/userlist';
// For Creating Saga and connecting store to saga middleware
import createSagaMiddleware from 'redux-saga';
import {getApiData} from './sagas/usersaga';
const sagaMiddleware = createSagaMiddleware();
const rootReducer = combineReducers({
res: contactReducer
})
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(getApiData);
ReactDOM.render(<Provider store={store}> <App /> </Provider>, document.getElementById('root'));
serviceWorker.unregister();
It successfully getting the data from the api and I successfully handle the data in acttion generated by 'receiveApiData' action generator function.
I want to call the getApiData function on a action which is genrated by function 'requestApiData' which is dispatched by. The action name is '{type: REQUEST_API_DATA}'
How to run Our getApiData on a action which is dispatched.
My userlist reducer file look like below
import * as actionTypes from "../actions";
const initialState = {
value: '',
results: []
};
const reducer = (state = initialState, action) => {
switch(action.type){
case actionTypes.STORE_CONTACTS: // This is for storing all contacts in the state here
console.log(action.values)
return {
...state,
results: action.values
}
case actionTypes.RECEIVE_API_DATA:
console.log(action);
return{
...state,
results: action.contacts
}
case actionTypes.DELETE_CONTACT:
return {
...state,
results: action.value
}
case actionTypes.ADD_CONTACT:
// perform add action to the database, update state and return All new data
return {
...state,
}
case actionTypes.EDIT_CONTACT:
return {
...state,
}
default:
return state;
}
};
export default reducer;

You need to use the takeEvery effect you are actually already importing in usersaga.js
So in usersaga.js add this saga:
export function* requestWatcher(action){
yield takeEvery('REQUEST_API_DATA', getApiData);
}
And in index.js run this saga instead of directly running the getApiData:
sagaMiddleware.run(requestWatcher);
This is one of the basic concepts of redux-saga and I really suggest reading the documentation https://redux-saga.js.org/docs/basics/UsingSagaHelpers.html

Related

Redux action not triggering reducers

Problem
I wired up my react application with a Redux store, added an api action to gather data from my backend including middleware redux-promise. Most everything seems to work as I can see my store in the React web editor along with the combine reducer keys. When I have my action called, it works and console logs the completed promise. However, my reducers never run. I thought it was an issue with my dispatch on the main container, but I've tried every way that I can think of at this point - regular dispatch() and bindActionCreators. HELP!
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import promiseMiddleware from 'redux-promise';
import RootReducer from './reducers';
const createStoreWithMiddleware = applyMiddleware(promiseMiddleware)(createStore)
let store = createStore(RootReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));`
Combine Reducers
import { combineReducers } from 'redux';
import ReducerGetPostings from './reducer_get_postings'
const rootReducer = combineReducers({
postingRecords: ReducerGetPostings
})
export default rootReducer;
Reducer
import { FETCH_POSTINGS } from '../actions/get_postings'
export default function (state = null, action) {
console.log('action received', action)
switch (action.type) {
case FETCH_POSTINGS:
return [ action.payload ]
}
return state;
}
Action API
import axios from 'axios';
import { url } from '../api_route';
export const FETCH_POSTINGS = 'FETCH_POSTINGS'
export function fetchpostings() {
const postingRecords = axios.get(`${url}/api/postings`)
console.log('Postings', postingRecords)
return {
type: FETCH_POSTINGS,
payload: postingRecords
};
}
Container
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { fetchpostings } from '../../actions/get_postings.js'
class Dashboard extends Component {
//....lots of other functionality already built here.
componentDidMount() {
axios.get(`${url}/api/postings`)
.then(res => res.data)
.then(
(postingRecords) => {
this.setState({
postingData: postingRecords,
postingOptions: postingRecords
});
},
(error) => {
this.setState({
error
})
}
)
// primary purpose is to replace the existing api call above with Redux Store and fetchpostings action creator
fetchpostings()
}
}
function mapDispatchToProps(dispatch) {
// return {actions: bindActionCreators({ fetchpostings }, dispatch)}
return {
fetchpostings: () => dispatch(fetchpostings())
}
}
export default connect(null, mapDispatchToProps)(Dashboard);
You are not dispatching your action, when you call fetchpostings() in componentDidMount you are calling the method imported from actions/get_postings.js, not the method that will dispatch.
Try this.props.fetchpostings() instead.
You also did not bind state to props you need to do that as well.

Function executes twice

I can't understand why my function returnSlidesReducer() executes twice.
I'm using Redux.
My reducer file slides.js is (reads json file and returns data to a store):
import jsonFile from '../sliderContent.json';
const returnSlidesReducer = (slidesContent) => {
console.log(slidesContent);
return slidesContent;
}
returnSlidesReducer(jsonFile);
export default returnSlidesReducer;
And my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {
createStore
} from 'redux';
//import allReducers from './reducers';
import SlidesReducer from './reducers/slides';
const store = createStore(SlidesReducer);
ReactDOM.render(
<App />,
document.getElementById('root')
);
In console I get:
{slider:Array(3)}
undefined
And because of this in a store I get undefined.
See the reducer from the example todo app in Redux doc:
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text])
default:
return state
}
}
let store = createStore(todos, ['Use Redux'])
You don't need to explicitly call your reducer function like you do.
If you want to use the json object as the initial state, you can pass it as the second argument to createStore(..)
createStore(returnSlidesReducer, jsonFile);
On a side note, your reducer function isn't of the standard redux reducer form. I recommend following the official Redux example.

React Redux - container/component not updating when passing data from reducer

I'm new to React, please keep this in mind.
I'm trying to render a list of recipes fetched from food2fork API but I can't get the view to update, even if the data is fetched correctly.
Here's recipe_list.js:
import React, { Component } from "react";
import { connect } from "react-redux";
class RecipesList extends Component {
// renderRecipe(recipe) {
// console.log(recipe);
// return (
// <div>{recipe}</div>
// );
// }
render() {
console.log("Render function ", this.props.recipes)
return (
<div>
<p>Recipes</p>
<div>{this.props.recipes}</div>
</div>
);
}
}
function mapStateToProps(state){
return { recipes: state.recipes };
}
export default connect(mapStateToProps)(RecipesList);
Here's reducer_recipes.js:
import FETCH_RECIPES from "../actions/index";
export default function(state = [], action){
switch (action.type) {
case FETCH_RECIPES:
return action.payload;
}
return state;
}
Here's /reducers/index.js:
import { combineReducers } from 'redux';
import RecipesReducer from "./reducer_recipes";
console.log(RecipesReducer);
const rootReducer = combineReducers({
recipes: RecipesReducer
});
export default rootReducer;
Here's /actions/index.js:
import axios from "axios";
const API_KEY = "****************************";
export const URL = `https://food2fork.com/api/search?key=${API_KEY}`;
export const FETCH_RECIPES = "FETCH_RECIPES";
export function fetchRecipes(term){
const url = `${URL}&q=${term}`;
const request = axios.get(url);
return {
type: FETCH_RECIPES,
payload: request
};
}
I don't get any specific error. The view just doesn't update. I tried to spread some console.log around the files to try to understand where the problem is.
It seems like the Reducer is not successfully delivering the payload to the component.
NOTE: I'm using react-promise so the promise returned from axios is automatically resolved.
Any ideas?
===================================================================
EDIT:
Thank you for the useful links but there is clearly something that I'm still missing here.
I have modified the action index:
function getStuffSuccess(response) {
return {
type: FETCH_RECIPES,
payload: response
};
}
function getStuffError(err) {
return {
type: ERROR_FETCH_RECIPES,
payload: err
};
}
export function fetchRecipes(term) {
const url = `${URL}&q=${term}`;
return function(dispatch) {
axios.get(url)
.then((response) => {
dispatch(getStuffSuccess(response));
})
.catch((err) => {
dispatch(getStuffError(err));
});
};
}
I have also included redux-thunk to the store:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from "redux-promise";
import Thunk from 'redux-thunk';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(Thunk, ReduxPromise) (createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
The behaviour hasn't changed from before. The view is still not updating.
NOTE: If I console.log the payload from the Reducer the data is in there. But when I try to do the same in the View nothing happens.
Your action is not synchronus here, you need to use Async Action to deliver the response to reducer, meaning, you have to dispatch the response instead of returning it. Check the given link for more details.
I would try refactoring your /actions/index.js like so:
import axios from 'axios';
export const FETCH_RECIPES = 'fetch_recipes';
export const CREATE_RECIPE = 'create_recipe';
const ROOT_URL = '<url-of-api-endpoint>';
const API_KEY = '<api-key>';
export function fetchRecipes() {
const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
return {
type: FETCH_RECIPES,
payload: request
};
}
export function createRecipe(values, callback){
const request = axios.post(`${ROOT_URL}/posts${API_KEY}`, values)
.then(() => callback());
return {
type: CREATE_RECIPE,
payload: request
}
}

Cannot read state from Redux store. What did I miss?

Here is my index.js where I initially dispatch an action to read my list of locations:
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import configureStore from './store/configureStore';
import {Provider} from 'react-redux';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import {loadLocationList} from './actions/locationActions';
import './css/styles.css';
const store = configureStore();
render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>,
document.getElementById('app')
);
Then here is my action where I get the data & then create an action out of it:
export function loadLocationListSuccess(alistingData) {
return { type: types.LOAD_LOCATION_LIST_SUCCESS, listingData: alistingData};
}
export function loadLocationList() {
return function(dispatch){ //we return a function that accepts a parameter, we just called it dispatch
//dispatch(fetchCallActions.fetchCallStart("")); // we dispatch a function fetchCallStart to indicate the start of our call, this is to keep in check with our asynchronous function calls
let link = 'http://example.com:8399/location';//our fetch url
console.log(link); //we log our link, just for debug purposes
return fetch(link) //start fetch
.then(function(response) {
return response.json();
}).then(function(json) {
dispatch(loadLocationListSuccess(json));
}).catch(function(ex) {
console.log('parsing failed', ex);
});
};
}
Then here is my reducer:
import * as types from '../actions/actionTypes';
export default function locationReducer(state = [], action) {
switch(action.type) {
case types.LOAD_LOCATION_LIST_SUCCESS:
return {listingData: action.listingData};
default:
return state;
}
}
Then here is my mapStateToProps & connect function:
function mapStateToProps(state, ownProps) {
return {
// we'll call this in our component -> this.props.listingData
listingData: state.listingData
};
}
export default connect(mapStateToProps, mapDispatchToProps)(homePage);
For some reason, it cannot read state.listingData or am I actually doing it wrongly? Anyone can help me with this problem?
I tried logging state.listingData and it showed undefined
Here is my configureStore:
import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../reducers';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk, reduxImmutableStateInvariant())
);
}
Here is my combined Reducer:
import {combineReducers} from 'redux';
import courses from './courseReducer';
import locations from './locationReducer';
const rootReducer = combineReducers({
courses,
locations
});
export default rootReducer;
Did I not connect it to the store properly?
Recent update:
Logging JSON.stringify(state) in mapStateToProps would actually shows the result. Thanks guys.
The correct path turned out to be state.locations.listingData because I think in my combined Reducer I included the reducer as locations so maybe thats why the state for it is state.locations. Hope this helps anyone with the problem.
Can you show the code of configureStore file? The problem might be there, may be you forgot to add reducer to list of reducers.
Does the action works right? Did you log data before dispatch(loadLocationListSuccess(json));?
UPD:
Because of rootReducer. Each reducer creates their own key in store. When you combine your reducers in rootReducer, like:
import locations from './locationReducer';
const rootReducer = combineReducers({
courses,
locations
});
It creates store with this kind of structure:
const store = {
courses: {},
locations: {}
}
So, after that you dispatched action and reducer changed the data to this:
const store = {
courses: {},
locations: {
listingData: someData
}
}
If you want to access to listingData like: state.listingData, you need to change a little your reducer and combineReducer to:
export default function listingData(state = {}, action) {
switch(action.type) {
case types.LOAD_LOCATION_LIST_SUCCESS:
return action.listingData;
default:
return state;
}
}
...
import listingData from './locationReducer';
const rootReducer = combineReducers({
courses,
listingData
});

Redux Router - "Dispatch is not defined"

I've got a simple component that calls an action when a user loads a page, and inside that action, I'm trying to dispatch another action to set the loggedIn state of the store to true or false:
import React, { Component } from 'react'
import { Link, browserHistory } from 'react-router'
import $ from 'jquery'
class Login extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.props.actions.guestLoginRequest()
}
render() {
return (
<div>
<div classNameName="container">
<div className="row">
We are signing you in as a guest
</div>
</div>
</div>
)
}
}
export default Login
I can get the login information when the guestLoginRequest action is called, but when I try to dispatch another action inside of it, nothing happens:
guestLoginRequest: function(){
var ref = new Firebase("https://penguinradio.firebaseio.com");
ref.authAnonymously(function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
return dispatch => {
dispatch(actions.setLoginStatus(true, authData))
console.log("dispatched");
};
}
});
}
I get an error of Uncaught ReferenceError: dispatch is not defined when I remove the return dispatch => { } statement. In my store I am using redux-thunk, so I can dispatch inside of actions:
// Store.js
import { applyMiddleware, compose, createStore } from 'redux'
import rootReducer from './reducers'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
let finalCreateStore = compose(
applyMiddleware(thunk, logger())
)(createStore)
export default function configureStore(initialState = { loggedIn: false }) {
return finalCreateStore(rootReducer, initialState)
}
I am mapping the dispatch to props in my app.js as well:
function mapStateToProps(state) {
return state
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
Just in case it could be helpful, here is my client.js and reducer files:
// client.js
import React from 'react'
import { render } from 'react-dom'
import App from '../components/App'
import configureStore from '../redux/store'
import { Provider } from 'react-redux'
let initialState = {
loggedIn: false
}
let store = configureStore(initialState)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
)
// Reducer.js
import { combineReducers } from 'redux'
let LoginStatusReducer = function reducer(loggedIn = false, action) {
switch (action.type) {
case 'UPDATE_LOGIN_STATUS':
return loggedIn = action.boolean
default:
return loggedIn
}
}
export default LoginStatusReducer
const rootReducer = combineReducers({
loggedIn: LoginStatusReducer
})
export default rootReducer
Any ideas why my dispatch function isn't working? I'm confused since I did set up redux-thunk with my store, and I'm using code similar to the docs when I call return dispatch => { }. Is there something I'm missing? Thank you in advance for any advice!
You need your action to return a function to utilize the thunk middleware, then redux will inject the dispatcher into it. You mixed your dispatcher invocation with the implementation detail. The following snippet fixes both defects.
guestLoginRequest: function(){
return function (dispatch) {
var ref = new Firebase("https://penguinradio.firebaseio.com");
ref.authAnonymously(function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
dispatch(actions.setLoginStatus(true, authData))
console.log("dispatched");
}
});
}
}
In addition, you need to dispatch your action correctly on the Login class.
dispatch(this.props.actions.guestLoginRequest())
Your action invocation is always done by invoking dispatch. The flow should be something like this:
React component --> dispatch ---> API call (thunk middleware) --> dispatch ---> reducer
Make sure useDispatch imported
import { useDispatch } from "react-redux";
First, you need to import
import { useDispatch } from "react-redux";
then call it.
const dispatch = useDispatch();
now you are ready for use.

Categories

Resources