It seems to ignore the Async / Await - reactjs

On a React page, I have a method called goOut. This method calls upon a Redux action > Node controller > Redux reducer. I can confirm that the correct data values are returned inside the Redux action, the controller method, and the reducer. However, nonetheless, at point 1 below inside the goOut method, it returns undefined.
What am I doing wrong / how could it return undefined if the the reducer is returning the correct values? It is as if the await inside the goOut method is not working...
React page:
import { go_payment } from "../../appRedux/actions/paymentAction";
<button onClick={this.goOut}>
Button
</button>
async goOut(ev) {
try {
const data = { user: parseInt(this.state.userId, 10) };
let result = await this.props.go_payment({data});
console.log(result);
// 1. RETURNS UNDEFINED. As if it tries to execute this line before it has finished the previous line.
{
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(
{go_payment}, dispatch
);
};
Redux Action:
export const go_payment = (data) => {
let token = getAuthToken();
return (dispatch) => {
axios
.post(`${url}/goController`, data, { headers: { Authorization: `${token}` } })
.then((res) => {
if (res.status === 200) {
// console.log confirms correct data for res.data
return dispatch({ type: GO_SUCCESS, payload: res.data });
})
}
}
Node controller method:
Returns the correct data in json format.
Reducer:
export default function paymentReducer(state = initial_state, action) {
switch (action.type) {
case GO_SUCCESS:
// console.log confirms action.payload contains the correct data
return { ...state, goData: action.payload, couponData: "" };
}
}

Related

React - useReducer with asynchronous CRUD operations

I am trying to figure out how to use useReducer with asynchronous CRUD operations (using the fetch API).
In my mind the reducer function would look like this:
async function reducer(action, state) {
const newState = {...state};
switch (action.type) {
case types.ADD_ITEM:
try {
const {item} = await addItem(action.payload.item);
newState.items.push(item);
}
catch (e) {
newState.error = e.message;
}
break;
case types.REMOVE_ITEM:
try {
await removeItem(action.payload.itemId);
newState.items = newState.items.filter(value.id !== action.payload);
}
catch (e) {
newState.error = e.message;
}
break;
case types.EDIT_ITEM:
try {
const {item} = await editItem(action.payload.itemId, action.payload.item);
newState.items[newState.items.findIndex(value => value.id === action.payload.itemId)] = item;
}
catch (e) {
newState.error = e.message;
}
break;
}
return newState;
}
These would be the fetch functions:
async function addItem(item) {
const response = await fetch('addItemRoute', {
method: "POST",
body: JSON.stringify({
item
})
});
return response.json();
}
async function removeItem(itemId) {
const response = await fetch('removeItemRoute/' + itemId, {
method: "DELETE"
});
return response.json();
}
async function editItem(itemId, item) {
const response = await fetch('editItemRoute/'+ itemId, {
method: "PUT",
body: JSON.stringify({
item
})
});
return response.json();
}
But the reducer function cannot be an async function.
What would be the standard way to handle concepts like this?
Any help/reference is truly appreciated.
I think you misunderstood the role of reducer. In React world, there is a thing call global state (a way to pass values down to children without having to pass as props), which traditionally being handled by another package called Redux. The reducer only handle taking whatever you dispatch, decide what action to take to update the global state based on the type of action which is not asynchronous. The action is what you use to decide what to dispatch and also the way for you to get the data to dispatch so usually all the HTTP calls occurs here. Since useReducer will returns for you the current state and the dispatch function as well, you can basically pass this dispatch to your action. You can take a look at my example below based on your example for clearer image of what you might want to do:
You may want to put all your action in a action file called action.js like this:
async function addItem(item, dispatch) {
const response = await fetch('addItemRoute', {
method: "POST",
body: JSON.stringify({
item
})
});
return dispatch({
type: "ADD_ITEM",
payload: response.json()});
}
async function removeItem(itemId, dispatch) {
const response = await fetch('removeItemRoute/' + itemId, {
method: "DELETE"
});
return dispatch({
type: "ADD_ITEM",
payload: response.json()
});
}
async function editItem(itemId, item, dispatch) {
const response = await fetch('editItemRoute/'+ itemId, {
method: "PUT",
body: JSON.stringify({
item
})
});
return dispatch({
type: "ADD_ITEM",
payload: response.json()
});
}
Then in your reducer, you can do the regular without having to call the fetch or async calls like this:
async function reducer(action, state) {
const newState = {...state};
switch (action.type) {
case types.ADD_ITEM:
try {
const {item} = action.payload;
newState.items.push(item);
}
catch (e) {
newState.error = e.message;
}
break;
case types.REMOVE_ITEM:
try {
newState.items = newState.items.filter(value.id !== action.payload);
}
catch (e) {
newState.error = e.message;
}
break;
case types.EDIT_ITEM:
try {
const {item} = action.payload;
newState.items[newState.items.findIndex(value => value.id === action.payload.itemId)] = item;
}
catch (e) {
newState.error = e.message;
}
break;
}
return newState;
}
Then in your component with the button that you want to execute this, you can do something like this:
const MyComponent = ()=> {
...
const [state, dispatch] = useReducer(reducer, initialState);
...
return (
...
<button onClick={addItem(item, dispatch)}/>
...
}
You can reference the core concept of redux here which IMO explains very clearly the functionality of reducer, dispatch, actions and global state. If you want you can also tried out Redux as well, here's their tutorial.

Access to API using Redux

I have a react-redux app. I need to call API and used it in my component. The app is called with fetch in function in utills.
All functions are group and export like this:
export const sportTeam = {
getBasketballTeam,
getBasketballTeamById,
}
function getBasketballTeam() {
let token = store.getState().UserReducer.token;
fetch(
actions.GET_BASKETBALLTEAM,
{
method: "GET",
headers: { Authorization: `Bearer ${token}` },
}
)
.then((res) => {
if (res.status == 200 ) {
return res.json();
}
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
}
getBasketballTeam contains an array of objects.
How can I get getBasketballTeam and used it in the component in the view to returning the list with this data?
You don't want your getBasketballTeam function to access the store directly through store.getState().
What you want is a "thunk" action creator that gets the store instance as an argument when you dispatch it.
The flow that you want is this:
Component continuously listens to the basketball team state with useSelector (or connect).
Component mounts.
Component dispatches a getBasketballTeam action.
Action fetches data from the API.
Reducer saves data from the action to the state.
State updates.
Component re-renders with the new data from state.
The easiest way to do this is with the createAsyncThunk function from Redux Toolkit. This helper handles all errors by dispatching a separate error action. Try something like this:
Action:
export const fetchBasketballTeam = createAsyncThunk(
"team/fetchBasketballTeam",
async (_, thunkAPI) => {
const token = thunkAPI.getState().user.token;
if ( ! token ) {
throw new Error("Missing access token.");
}
const res = await fetch(actions.GET_BASKETBALLTEAM, {
method: "GET",
headers: { Authorization: `Bearer ${token}` }
});
if (res.status !== 200) {
throw new Error("Invalid response");
}
// what you return is the payload of the fulfilled action
return res.json();
}
);
Reducer:
const initialState = {
status: "idle",
data: null
};
export const teamReducer = createReducer(initialState, (builder) =>
builder
.addCase(fetchBasketballTeam.pending, (state) => {
state.status = "pending";
})
.addCase(fetchBasketballTeam.fulfilled, (state, action) => {
state.status = "fulfilled";
delete state.error;
state.data = action.payload;
})
.addCase(fetchBasketballTeam.rejected, (state, action) => {
state.status = "rejected";
state.error = action.error;
})
);
Store:
export const store = configureStore({
reducer: {
team: teamReducer,
user: userReducer,
}
});
Component:
export const BasketballTeam = () => {
const { data, error, status } = useSelector((state) => state.team);
const dispatch = useDispatch();
useEffect(
() => {
dispatch(fetchBasketballTeam());
},
// run once on mount
// or better: take the token as an argument and re-run if token changes
[dispatch]
);
if (status === "pending") {
return <SomeLoadingComponent />;
}
if (!data) {
return <SomeErrorComponent />;
}
// if we are here then we definitely have data
return <div>{/* do something with data */}</div>;
};
After you get response you need to do the following things
call dispatch function to store the data received in REDUX state.
Now when you have data in redux state, you can use useSelector() to get that state and make use of it in your jsx file.

action.payload in creactAsyncThunk is undefined

I am trying to get user data from api using axios with createAsyncThunk, and want the user data to be stored in state by the fulfilled action dispatched by the createAsyncThunk.
As mentioned in the docs
if the promise resolved successfully, dispatch the fulfilled action with the promise value as action.payload.
But the action.payload in undefined in the fulfilled action creator.
Here is my code.
/// Create Async Thunk
export const fetchUserData = createAsyncThunk(
'user/fetchUserData',
(payload, { dispatch }) => {
axios
.get('/user')
.then(res => {
console.log(res.data);
//Used this as a work around for storing data
dispatch(setUser(res.data));
return res.data;
})
.catch(err => {
console.error(err);
return err;
});
}
);
/// On Fulfilled
const userSlice = createSlice({
...
extraReducers:{
...
[fetchUserData.fulfilled]: (state, action) => {
// Payload is undefined
state.data = action.payload
},
}
}
createAsyncThunk accepts two parameters:
type
payloadCreator
Where payloadCreator is a callback function that should return a promise (containing the result of some asynchronous logic) or a value (synchronously).
So, you can either write:
export const fetchUserData = createAsyncThunk(
'user/fetchUserData',
(payload, { dispatch }) => {
return axios.get('/user'); // Return a promise
}
);
or
export const fetchUserData = createAsyncThunk(
'user/fetchUserData',
async (payload, { dispatch, rejectWithValue }) => {
try {
const response = await axios.get('/user')
return response // Return a value synchronously using Async-await
} catch (err) {
if (!err.response) {
throw err
}
return rejectWithValue(err.response)
}
}
);
An addition to #Ajeet Shah's answer:
According to the documentation a rejected promise must return either
an Error-instance, as in new Error(<your message>),
a plain value, such as a descriptive String,
or a RejectWithValue return by thunkAPI.rejectWithValue()
With the first two options, and I haven't tested the last option, the payload will also by undefined, but an error parameter will be given containing your rejected message.
See this example:
const loginAction = createAsyncThunk(
"user/login",
(payload, { getState }) => {
const { logged_in, currentRequestId, lastRequestId } = getState().login;
// Do not login if user is already logged in
if (logged_in) {
return Promise.reject(new Error(Cause.LoggedIn));
}
// Do not login if there is a pending login request
else if (lastRequestId != null && lastRequestId !== currentRequestId) {
return Promise.reject(new Error(Cause.Concurrent));
}
// May as well try logging in now...
return AccountManager.login(payload.email, payload.password);
}
);

How to Create Middleware for refresh token in Reactjs with axios and redux

i am working with reactjs on front end the issue is after certain time period the accessToken is expired and server send status of 401(unauthorized) then i need to send refresh token back to server it works fine until i manually send the refresh token i set the setInterval function but thats not a good approach how to automatically send it when token is expired.
i also google it but everyone is talking about creating middleware anyone please give me the hint how to create that middleware or any other solution or link any article related to it . i created this but this didnt works for me however when server send status of 401 then middleware ran but it dosent dispatch my refreshToken() function
const customMiddleWare = store => next => action => {
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
if(error.status === 401) {
// do something when unauthorized
store.dispatch(refreshToken());
}
return Promise.reject(error);
});
console.log("Middleware triggered:", action);
next(action);
}
By the way i am using redux, redux-thunk and axios. thanks,
some time ago i used to use the next way:
First of all i created some api folder, where each function returns data for axios requests
// /api.js
export function signIn (data) {
return {
method: 'post',
api: '/sign-in'
data: data
}
}
export function signUp (data) {
return {
method: 'post',
api: '/registration'
data: data
}
}
then i generated action type by specific rule, like: SIN_IN_REQUEST, where: SIGN_IN means signIn function in /api.js; REQUEST means that you need to do api request. As result my middleware looked like the next:
// request middleware
const instance = axios.create({
baseURL: '/api'
});
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}
const customMiddleWare = store => next => action => {
if (!action.type.endsWith('_REQUEST')) {
next();
return;
}
const methodName = action.type.replace('_REQUEST', ''); // removed _REQUEST from action type
const camelCaseMethodName = camelize(methodName); // the result is "signIn"
const method = api[camelCaseMethodName];
if (!method) {
next();
return;
}
const dataForRequest = method(action.payload);
try {
const response = await instance(dataForRequest);
const newActionType = action.type.replace('_REQUEST', '_SUCCESS');
dispatch({
type: newActionType,
payload: {
requestPayload: action.payload,
response: response,
}
})
} catch(error) {
if (error.status === '401') {
dispatch(refreshToken());
next();
return;
}
const newActionType = action.type.replace('_REQUEST', '_FAILURE');
dispatch({
type: newActionType,
payload: {
requestPayload: action.payload,
error: error,
}
})
}
next();
}
After that you can easily manage any api request in your application like that:
function someTHunkMethod(username, password) {
return (dispatch, getState) => {
dispatch({
type: 'SIGN_IN_REQUEST',
payload: {
username,
password
}
})
}
}
function oneMoreThunk(data) {
return (dispatch, getState) => {
dispatch({
type: 'GET_USERS_REQUEST',
payload: data
})
}
}
And in reducer do something like that
...
switch (action.type) {
case 'SIGN_REQUEST':
return {
isLoading: true,
user: null
}
case 'SIGN_SUCCESS':
return {
isLoading: false,
user: action.payload.response.data
}
case 'SIGN_FAILURE':
return {
isLoading: false,
user: null
}
default:
return state
}

How do I update Redux store with POST response?

I have an application that is using React, Redux (Redux Thunk). I having an issue updating the state in the reducer after a fetch post inserts into a table.
I am trying to dispatch an action and pass some information from the action to the reducer but not able to do so. I am specifically trying to pass the fetch response into the dispatch. I have a key named res within my dispatch. I set it to a value of data but I believe this value of data is undefined.
export function insertSearchTerm(searchTerm) {
console.log('C')
return (dispatch) => {
fetch('http://localhost:3001/api/v1/searches?searchterm='+ searchTerm, {
headers: {
'Content-Type':'application/json', //headers - tells y9ou that it is json
},
method:'POST',
body: JSON.stringify(searchTerm) //stringifies searchTerm
}).then(res => console.log('Inside insertSearch Term resp', res.json()))
.then(data => {
dispatch({
type:'INSERT_SEARCH_TERM',
searchTerm: searchTerm,
res : data
})
}
)
}
console.log('E')
}
export default function allSearchTermsReducer(state = {allSearchTerms: []}, action) {
switch (action.type) {
case 'ALL_SEARCHES':
console.log("Allsearch reducer",action.payload);
return {...state, allSearchTerms: action.payload}
case 'INSERT_SEARCH_TERM':
console.log('insert search term action', action)
return {
...state,
allSearchTerms: [...state.allSearchTerms, action.id, action.searchTerm, action.created_at] }
default:
return state
}
};
In your action-creator, for the first .then block you are returning a console.log() not the data itself. So there's no data to dispatch in the proceeding .then block. Should be updated to:
export function insertSearchTerm(searchTerm) {
console.log('C')
return (dispatch) => {
fetch('http://localhost:3001/api/v1/searches?searchterm='+ searchTerm, {
headers: {
'Content-Type':'application/json', //headers - tells y9ou that it is json
},
method:'POST',
body: JSON.stringify(searchTerm) //stringifies searchTerm
}).then(res => res.json())
.then(data => {
dispatch({
type:'INSERT_SEARCH_TERM',
searchTerm: searchTerm,
res : data
})
}
)
}
console.log('E')
}

Resources