score:2
with saga
the returned value from calling dispatch
is just the action that you dispatched. your saga will "take" this action and dispatch additional actions, but that is all considered independent. so your res
variable is just the original action postspotifyalbums(obj)
.
or there's no way so then i need to make a second call to the reducer to give me back the just inserted obj?
yes, you would need to have a useselector
in the component that is listening for the posted value.
with thunk
this is a lot easier to do with redux-thunk because the thunk middleware overrides the default behavior of dispatch
. when you dispatch a thunk (an action creator which is a function of dispatch
) then you get back the value that's returned by the thunk.
any return value from the inner function will be available as the return value of dispatch itself. this is convenient for orchestrating an asynchronous control flow with thunk action creators dispatching each other and returning promises to wait for each other's completion - docs
action
const postspotifyalbums = (payload) => async (dispatch) => {
dispatch({ type: "post_spotify_albums_pending" });
const args = {
method: "post",
url: baseurl,
params: {
token: payload.token,
albumcode: payload.albumcode,
albumgenres: payload.albumgenres,
usercode: payload.usercode
}
};
try {
const spotifycategories = await axios.request(args);
dispatch({
type: "post_spotify_albums_success",
payload: spotifycategories.data
});
// we can customize the returned value here to anything!
return spotifycategories.data;
} catch (error) {
console.log(error);
dispatch({ type: "post_spotify_albums_error", payload: error });
}
};
component
const dodispatch = async () => {
// we get back whatever we specifically returned in the thunk
const data = await dispatch(postspotifyalbums(obj));
console.log("result", data);
// we didn't return anything in the error case so it would be undefined
if (data) {
// do something with success
}
};
with createasyncthunk
redux-toolkit includes a helper function createasyncthunk that automatically creates "pending" "rejected" and "fulfilled" actions in one step. the return value here is the final action that was dispatched.
when dispatched, the thunk will ... return a fulfilled promise containing the final dispatched action (either the
fulfilled
orrejected
action object) - docs
action
const postspotifyalbums = createasyncthunk(
"post_spotify_albums",
async (payload) => {
const args = {
method: "post",
url: baseurl,
params: {
token: payload.token,
albumcode: payload.albumcode,
albumgenres: payload.albumgenres,
usercode: payload.usercode
}
};
const spotifycategories = await axios.request(args);
return spotifycategories.data;
}
);
component
const dodispatch = async () => {
const action = await dispatch(postspotifyalbums(obj));
console.log("result", action);
// we could have the success or the failure action
if ( action.type === postspotifyalbums.fulfilled.type) {
// do something with success
const data = action.payload;
} else {
// do something with error
const error = action.error;
}
};
score:1
not sure if you are still looking for the solution or not, but here's my implementation of the code. flow goes like this.
- we make dispatch request from our component
- redux dispatches action called "initiate_transaction".
- redux saga intercepts the action and starts making api call based on that
- api call is successful and "initiate_transaction_success" is dispatched with the api's value.
- now saga returns value from the axios to the actual calling function from where the step 1 dispatch was called.
here's the code.
// store.js
import {middleware as thunkmiddleware} from 'redux-saga-thunk';
const middlewares = [thunkmiddleware];
const sagamiddleware = createsagamiddleware();
middlewares.push(sagamiddleware);
if (process.env.node_env === `development`) {
const {logger} = require(`redux-logger`);
middlewares.push(logger);
}
const persistconfig = {
key: 'root',
storage: asyncstorage,
white: ['errors'],
};
const persistedreducer = persistreducer(persistconfig, rootreducer);
const store = configurestore({
reducer: persistedreducer,
middleware: middlewares,
devtools: process.env.node_env === `development` ? true : false,
});
// payment.js(or any of your component)
const handlebtnclick = async (type, value) => {
console.log('btn click type', type, route.params, value);
switch (type) {
case 'pay':
try {
let orderid = 'od_' + moment().format('yyyymmddhhmmss');
// here we are dispatching action "initiate_transaction" to redux saga.
// step 1.
const response = await props.initiatepayment({
orderid,
orderamount: 10,
ordercurrency: 'inr',
});
console.log('response', response.data.cftoken);
}catch (error){
console.log('error', error)
}
break;
}
// middleware used is redux-saga-thunk, which basically implements functionality of thunk in redux saga. so meta: {thunk: true} waits for the whole execution to finish and then continues.
// step 2
export const initiatepayment = data => ({
type: initiate_transaction,
data,
meta: {thunk: true},
});
//step 3
// here post is just a custom function for api call, onerror and onsuccess are the handler functions and safe is the wrapper method which basically implements try catch logic and handles errors for us without repeating much of the code.
// paymentsaga.js
function* initiatetransactionsaga({data, meta}) {
const response = yield call(post, api.initiate_transaction, data);
return response; //step 4....
}
export default function* paymentsaga() {
yield takelatest(
initiate_transaction,
safe(onerror, initiatetransactionsaga, onsuccess), //onsuccess required if you want values to be returned to step 1
);
}
// axiosapi.js
export async function post(url, data, config = {}) {
console.log('url data config', url, data, config);
return axiosapi
.post(url, {...data}, {...config})
.then(response => response.data);
}
// sagahelper.js
/**
* @param handler --- error handler function. in our case, onerror function
* @param saga --- actual saga function. in our case api is called and data is returned
* @param success --- success redux action dispatch function -- in our case, if we need to pass response coming from api to the actual calling function( something like props.viewingitem(data)), then pass it here, otherwise leave it blank
* @
*/
export const safe = (
handler: any = null,
saga: any,
success: any = null,
...args: any
) =>
function* (action: any) {
try {
console.log('action in safe===', action, success);
const res1 = yield call(saga, ...args, action);
// success wrapper. if you pass onsuccess method, then only this part will be executed. if you do not want the values to be returned from redux-saga to your component function call, then i suggest you skip it.
if (success) {
yield call(success, res1, action.type, action.meta);
return res1; //this line returns value to the component function( to step 1)
}
} catch (err) {
yield call(handler, ...args, err, action.type, action.meta);
}
};
export function* onerror(err: any, type: any, meta: any) {
console.log('type onerror', type);
yield put({
type: type + '_error',
payload: err,
error: true,
meta,
});
// do something with the error msg. like show alert, etc...
return err;
}
export function* onsuccess(response: any, type: any, meta: any) {
console.log('type onerror', response);
yield put({
type: type + '_success',
payload: response,
error: false,
meta,
});
// do something with the success msg. like show alert, etc...
return response;
}
you can find detailed information over here. https://medium.com/@dhavaljavia.p/redux-saga-return-values-from-saga-to-your-component-using-redux-saga-thunk-17ad6e9e81ef
Source: stackoverflow.com
Related Query
- React with Redux Saga - How to get data back from axios call
- How to get data from axios call in redux action? React JS search project
- how to get spesific data from api with axios and react js?
- How do I access data returned from an axios get to display on a web page using react js?
- How to fetch data in getInitialProps with redux-saga.Then get the response from redux store while in the getInitialProps method?
- How to Assign react redux state api get data using axios
- how to get images from mongo with axios and display them with react
- How to do Basic Authentication from React Axios GET call to a SpringBoot microservice
- React Router Link with params not reloading page with new data from componentDidMount and Redux axios data fetching
- How can I get the right data from database with react
- use axios with react to get data from api
- React redux frontend not fetching data from Django API with axios
- how to get config data from appsettings.json with asp.net core & react
- How to get the data from Redux store using class components in React
- how to get, by a get from axios, data in useState with react functionnal component
- How to get data back from reducer with a async action
- How do I configure axios in react to retrieve data with an objects id from an api?
- How to get a single data element from the database with Redux and React?
- How to call a function from different component using React with Redux Form?
- get data from server using axios with react
- How can I store the data I get from a Promise back into an object with the same key it came from?
- How to render React Component with data from Redux store
- How to get classname or props from NavLink to use with google tag manager with react and redux in a stateless functional component?
- How do I get my view to update after an item was removed from my store/State in React with Redux
- react get data from rest api with axios and and useEffect redering empty array plus array with data
- How to fill users variable with data from GET request in React
- how to get data from localhost:9200 (elasticsearch) using axios in react
- how to write one GET api call using axios instance with and without params in React JS
- How to get data from React aplication on Express server to update meta-tags with data fetched from API
- How to concatenate URL and string, and get data from API at click a button using axios in REACT JS
More Query from same tag
- react-router-dom v6 TypeScript withRouter for class components
- (Next/react) SWR refresh from button click in child component - can I use a callback?? (function to function)
- Is it possible to run React project without npm start?
- <Table> in react-bootstrap - SyntaxError
- TypeError: items is undefined while using DRF Api
- ReactJS, React-Router: Calling parent function
- Safely access a property inside a nested javascript object
- Arrays and React
- Why state returned from my reducer is an empty object??(React-Redux)
- How can I get React to Replace (not Merge) VDOM?
- How to ask for permission to download files on NextJS?
- React: react-router-dom's Redirect is not reloading page but changes the URL
- setInterval only executes once
- Building Dropdown component
- concatenate two variables in react
- 'Cannot destructure property of as it is undefined' during map
- Uncaught TypeError: Cannot read property 'Active' of undefined
- Is it okay to use map as a for loop without returning
- Using class member not state
- TextField Style using styed-components and Material-UI withStyles
- How to toggle class using React Hooks as per localstorage value in App.js?
- React, setState with async updater parameter?
- useEffect runs api request after I refresh the page
- MongoDB Put/ Update :: TypeError: {(intermediate value)} is not a function
- How to Implement dynamic routing in routes.js for generated menu items in sidebar in universal react redux boilerplate by erikras
- Is there a way to detect when data used by a query is evicted from the Apollo Client cache?
- How to make data fetching work together with Redux Toolkit and React Hooks?
- By clicking on HomePage button I want to show one component and by clicking on Cart button I want to show the other component (using boolean value)
- Route Order With Multiple Dynamic Params
- Get object data and target element from onClick event in react js