Fetch and dispatch in a redux action function - reactjs

In my react/redux project, I call a function from my action to fetch a data from an api. Fetch starts the api request... but react doesn't recognize dispatch()
function getAuthenticatedUser() {
....
return fetch("my.api/path", requestHeaders)
.then(response => handleResponse(response))
.then(response=>{
return response.json()
}).then(responseJson =>{
dispatch(requestSuccess(responseJson.user))
})
....
function requestSuccess(....
....
Then, I wrapped around return dispatch as follows. Now it outputs no error, but fetch() doesn't start any api requests. (No requests in Network/XHR)
return dispatch => {
return fetch("my.api/path", requestHeaders)
.then(response => handleResponse(response))
.then(response=>{
return response.json()
}).then(responseJson =>{
dispatch(requestSuccess(responseJson.user))
})
}
What am I missing?

I found the solution. Firstly I want to thanks to 3 comments on the question.
I firstly installed redux-thunk. I added a middleware to my store:
import thunk from "redux-thunk";
...
export const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
Than, I imported store in my component and dispatched my action function. (Previously I was calling it directly)
constructor(props) {
....
store.dispatch(userActions.getAuthenticatedUser())
Now fetch and dispatchers within fetch work fine.

Related

How to get data using Axios and store it in Redux store?

I've a individual file to get the data from Api and
const FetchLanguageList = () => {
const [isLanguage, setIsLanguage] = useState(true);
API.get(`en/restaurants/1/languages`)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.warn(err);
});
};
export default FetchLanguageList;
How Do I store the console.log(res.data) to my redux store?
For now I've nothing inside my store, and have default template counter slice.
I want to get the API data and store it in redux store, then dispatch the data to my UI componenet.
You can either do the API call inside of this function and make dispatch to your redux store with the data received or you could use something like redux-thunk or redux-sagas to fetch the data inside of your dispatch (which I would recommend as it would simplify the logic inside of your component)

How to dispatch data to redux from the common api request file?

I have created a common js file to call the service requests. I want to store the fetched data in my redux managed store. But I am getting this error saying Invalid hook call. Hooks can only be called inside of the body of a function component.I think this is because I am not using react-native boilerplate for this file. But the problem is I don't want to I just want to make service requests and responses.
import { useDispatch } from "react-redux";
import { addToken } from "../redux/actions/actions";
const { default: Axios } = require("axios");
const dispatch = useDispatch();
const handleResponse=(response, jsonResponse)=> {
// const dispatch = useDispatch(); //-----also tried using dispatch here
const jsonRes = jsonResponse;
const { status } = response;
const { errors } = Object.assign({}, jsonRes);
const resp = {
status,
body: jsonResponse,
errors,
headers: response.headers,
};
console.log(resp, 'handle response');
return await dispatch(addToken(resp.body.token))
};
const API = {
makePostRequest(token) {
Axios({
url: URL,
...req,
timeout: 30000
}).then(res =>
console.log('going to handle');
await handleResponse(res, res.data)
})
}
export default API
I know there would be some easy way around but I don't know it
Do not use useDispatch from react-redux, but dispatch from redux.
You need to use redux-thunk in your application.
Look at the example in this article Redux Thunk Explained with Examples
The article has also an example of how to use redux with asynchronous calls (axios requests in your case).
I suggest to refactored your api to differentiate two things:
fetcher - it will call your api, e.g. by axios and return data in Promise.
redux action creator (thunk, see the example in the article) - it will (optionally) dispatch REQUEST_STARTED then will call your fetcher and finally will dispatch (REQUEST_SUCCESS/REQUEST_FAILURE) actions.
The latter redux action creator you will call in your react component, where you will dispatch it (e.g. with use of useDispatch)

Calling dispatch inside redux middleware

I am trying to integrate redux-simple-auth in my existing reudx API. My old implementation used the native fetch and I added headers etc.. This new module provides a fetch replacement however it returns a redux action and am having a bit of a struggle figuring out how to set things up.
My store:
function configureStore (initialState) {
const middlewares = [
authMiddleware, // This is from rediux-simple-auth
apiMiddleware, // My own middleware
thunk
]
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(...middlewares), getInitialAuthState({ storage }))
)
}
My middleware simplified:
import { fetch } from 'redux-simple-auth'
export default store => next => action => {
...
next(my start action...)
return store.dispatch(fetch(API_ROOT + endpoint, { method }))
.then(response => {
next(my success/fail action...)
})
}
When I run this I can see my start and fail actions in redux inspector but not the fetch one (which does trigger a FETCH one)
If I call next instead of store.dispatch then it works in the sense that it tiggers the action but it does not return a promise I cannot get results.
How can I fix this flow?
next is not dispatch. Try this:
export default ({dispatch}) => next => action => ...
Use dispatch to dispatch your new action and use next(action) to pass the original action to the next middleware.

Use getState to access key in redux state for API call

I'm a little new to using thunk getState I have been even trying to console.log the method and get nothing. In state I see that loginReducer has they key property which I need to make API calls. status(pin): true
key(pin): "Ls1d0QUIM-r6q1Nb1UsYvSzRoaOrABDdWojgZnDaQyM"
Here I have a service:
import axios from 'axios'
import {thunk, getState} from 'redux-thunk'
import MapConfig from '../components/map/map-config'
const origin = 'https://us.k.com/'
class KService {
getNorthAmericaTimes() {
return (dispatch, getState) => {
const key = getState().key
console.log('This is time key,', key)
if (key) {
dispatch(axios.get(`${origin}k51/api/datasets/k51_northamerica?key=${key}`))
}
}
// const url = `${origin}k51/api/datasets/k51_northamerica?key=${urlKey}`
// return axios.get(url)
}
}
export default new K51Service()
However in my corresponding action I get that Uncaught TypeError: _kService2.default.getNorthAmericaTimes(...).then is not a function
This is what the action function looks like :
export function getKNorthAmericaTime(dispatch) {
KService.getNorthAmericaTimes().then((response) => {
const northAmericaTimes = response.data[0]
dispatch({
type: ActionTypes.SET_NORTH_AMERICA_TIMES,
northAmericaTimes
})
})
}
I'm assuming it probably has to do with the if block not getting executed.
You should move your axios.get() method to your action creator and pass the promise to redux thunk, then when the promise is resolved dispatch the action with the response data so it can be processed by the reducer into the app's state.
actions
import axios from "axios";
export function fetchData() {
return (dispatch, getState) => {
const key = getState().key;
const request = axios.get();// use your request code here
request.then(({ response}) => {
const northAmericaTimes = response.data[0]
dispatch({ type: ActionTypes.SET_NORTH_AMERICA_TIMES, payload: northAmericaTimes});
});
};
}
Here's a very simple example of using axios with redux-thunk:
https://codesandbox.io/s/z9P0mwny
EDIT
Sorry, I totally forgot that you need to go to the state before making the request.
As you can see go to the state in your function, get the key from it, make the request and when the promise is resolved, dispatch the action with the response data. I've updated the live sample so you can see it working.
Again sorry...

react-redux not dispatching thunk api call

I'm taking a working web version with redux and Api calls and porting them to a React Native app. However I notice when trying to dispatch a thunk to make an API call, I can't seem to see a console log in my thunk to confirm the dispatch. This makes me think something is not connected properly but I just don't see what that is. What am I missing?
I create a store with an initial state: When I log store.getState() everything looks fine.
const initialState = {
config: fromJS({
apiUrl: "http://localhost:3000/account-data",
})
}
const store = createStore(
reducers,
initialState,
compose(
applyMiddleware(thunk),
)
)
I use mapDispatchToProps and I see the functions in my list of props
export function mapDispatchToProps(dispatch) {
return {
loadProducts: () => dispatch(loadProducts())
};
}
However, when I inspect my loadProducts function, I do not see a console log confirming the dispatch. What's going on here? Why is loadProducts not dispatching? On the web version I'm able to confirm a network request and logs. On React Native I do not see a network request or these console logs.
export function loadProductsCall() {
console.log('in RN loadProductsCall') //don't see this
const opts = constructAxpOpts();
return {
[CALL_API]: {
types: [
LOAD_REQUEST,
LOAD_SUCCESS,
LOAD_FAILURE
],
callAPI: (client, state) =>
client.get(`${state.config.get('apiUrl')}/members`, opts),
shouldForceFetch: () => false,
isLoaded: state => !!(state.core.resources.products.get('productsOrder') &&
state.core.resources.products.get('productsOrder').length),
getResourceFromState: (state) => state.core.resources.products.toJS(),
isLoading: state => !!state.core.resources.products.get('isLoading'),
getLoadingPromise: state => state.core.resources.products.get('loadingPromise'),
payload: {}
}
};
}
export function loadProducts() {
console.log('in loadProducts') //don't see this
return (dispatch) =>
console.log('in loadProducts dispatched 2') //don't see this either
dispatch(loadProductsCall())
.then((response) => {
return response;
});
}
This code is missing custom API middleware that handles three action types. Also, in mapDispatchToProps a function is wrapping the dispatch. This function need to either be unwrapped and return a promise or called somewhere else in the code.

Resources