When useEffect is executed, I want to get the token through AsyncStorage, then get the data value through the axios.post ('/auth/me') router and execute the KAKAOLOG_IN_REQUEST action with disaptch.
As a result of checking the data value with console.log, the data value came in well. But when I run my code, this error occurs.
Possible Unhandled Promise Rejection (id: 1):
Error: Actions may not have an undefined "type" property. Have you misspelled a constant?
Error: Actions may not have an undefined "type" property. Have you misspelled a constant?
how can i fix my code?....
this is my code
(index.js)
const App = ({}) => {
const dispatch = useDispatch();
useEffect(() => {
async function fetchAndSetUser() {
const token = await AsyncStorage.getItem('tokenstore', (err, result) => {
});
var {data} = await axios.post(
'/auth/me',
{},
{
headers: {Authorization: `Bearer ${token}`},
},
);
console.log("data:",data);
dispatch({
type: KAKAOLOG_IN_REQUEST,
data: data,
});
}
fetchAndSetUser();
}, []);
return <Navigator />;
};
export {App};
(reducer/user.js)
import {
KAKAOLOG_IN_FAILURE,
KAKAOLOG_IN_REQUEST,
KAKAOLOG_IN_SUCCESS,
} from '../reducers/user';
function* watchkakaoLogIn() {
yield takeLatest(KAKAOLOG_IN_REQUEST, kakaologIn);
}
function* kakaologIn(action) {
try {
// const result = yield call(kakaologInAPI, action.data);
yield put({
type: KAKAOLOG_IN_SUCCESS,
data: action.data,
});
} catch (err) {
console.error(err);
yield put({
type: KAKAOLOG_IN_FAILURE,
error: err.response.data,
});
}
}
export default function* userSaga() {
yield all([
fork(watchkakaoLogIn),
]);
}
(reducer/index.js)
import { combineReducers } from 'redux';
import user from './user';
import post from './post';
// (이전상태, 액션) => 다음상태
const rootReducer = (state, action) => {
switch (action.type) {
// case HYDRATE:
// // console.log('HYDRATE', action);
// return action.payload;
default: {
const combinedReducer = combineReducers({
user,
post,
});
return combinedReducer(state, action);
}
}
};
export default rootReducer;
(src/index.js)
import {KAKAOLOG_IN_REQUEST} from '../sagas/user';
const App = ({}) => {
const dispatch = useDispatch();
useEffect(() => {
async function fetchAndSetUser() {
try {
const token = await AsyncStorage.getItem('tokenstore');
const {data} = await axios.post(
'/auth/me',
{},
{
headers: {Authorization: `Bearer ${token}`},
},
);
console.log('data::::::', data);
dispatch({
type: 'KAKAOLOG_IN_REQUEST',
data: data,
});
} catch (error) {
}
}
fetchAndSetUser();
}, []);
return <Navigator />;
};
export {App};
Issue
The error message is saying your code can throw an error and it isn't handled. It is also saying that KAKAOLOG_IN_REQUEST is undefined for some reason (perhaps you forgot to import it, or it is really a string).
Solution
Surround your asynchronous code in a try/catch. Define KAKAOLOG_IN_REQUEST or pass as a string "KAKAOLOG_IN_REQUEST".
useEffect(() => {
async function fetchAndSetUser() {
try {
const token = await AsyncStorage.getItem('tokenstore');
const {data} = await axios.post(
'/auth/me',
{},
{
headers: { Authorization: `Bearer ${token}` },
},
);
console.log("data:",data);
dispatch({
type: 'KAKAOLOG_IN_REQUEST',
data: data,
});
} catch(error) {
// handle error, logging, etc...
}
}
fetchAndSetUser();
}, []);
Related
I am using Next.js. I have created an Axios interceptor where a rejected Promise will be returned. But where there is a server-specific error that I need. Next.js is showing the error in the application like this.
And there is the code of the Axios interceptor and instance.
import axios from "axios";
import store from "../redux/store";
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
let token = "";
if (typeof window !== 'undefined') {
const item = localStorage.getItem('key')
token = item;
}
const axiosInstance = axios.create({
baseURL: publicRuntimeConfig.backendURL,
headers: {
Authorization: token ? `Bearer ${token}` : "",
},
});
axiosInstance.interceptors.request.use(
function (config) {
const { auth } = store.getState();
if (auth.token) {
config.headers.Authorization = `Bearer ${auth.token}`;
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
axiosInstance.interceptors.response.use(
(res) => {
console.log(res)
return res;
},
(error) => {
console.log(error)
return Promise.reject(error);
}
);
export default axiosInstance;
Also, I am using redux and there is the action.
import axios from "../../api/axios";
import { authConstants } from "../types";
export const login = (data) => {
return async (dispatch) => {
try {
dispatch({
type: authConstants.LOGIN_REQUEST,
});
const res = axios.post("/user/login", data);
if (res.status === 200) {
dispatch({
type: authConstants.LOGIN_SUCCESS,
payload: res.data,
});
}
} catch (error) {
console.log(error, authConstants);
dispatch({
type: authConstants.LOGIN_FAILURE,
payload: { error: error.response?.data?.error },
});
}
};
};
Your problem is here...
const res = axios.post("/user/login", data);
You're missing await to wait for the response
const res = await axios.post("/user/login", data);
This fixes two things...
Your code now waits for the response and res.status on the next line will be defined
Any errors thrown by Axios (which surface as rejected promises) will trigger your catch block. Without the await this does not happen and any eventual promise failure bubbles up to the top-level Next.js error handler, resulting in the popup in your screenshot.
How to make RTK Query createApi's mutation throw rejection?
The current code execution will enter then, How to get here.
getList({ id }).catch(() => { How to get here });
baseQuery.js
import { fetchBaseQuery, retry } from '#reduxjs/toolkit/query/react';
const baseQueryWithRetry = retry(
fetchBaseQuery({
baseUrl: process.env.REACT_APP_BASE_URL,
}),
{ maxRetries: 6 }
);
export const baseQueryWithReauth = async (args, api, extraOptions) => {
try {
const result = await baseQueryWithRetry(args, api, extraOptions) as { data: { RES: string } };
if (result.data.RES) {
const { body } = JSON.parse(result.data.RES);
switch (body.code) {
case '000000':
return { ...result, data: body }
default:
debugger
throw new Error('body.message');
}
}
return result;
}
catch (err: any) {
debugger
return Promise.reject(err);
}
}
services.js
import { createApi } from '#reduxjs/toolkit/query/react';
import { baseQueryWithReauth } from './baseQuery';
export const quoteApi = createApi({
reducerPath: 'quoteApi',
baseQuery: baseQueryWithReauth,
endpoints: (builder) => ({
getList: builder.mutation<any, object>({
query: (body) => ({
url: 'getPriceList',
method: 'POST',
body,
}),
}),
}),
refetchOnReconnect: true,
});
This is so that your application is not littered with uncaught async exceptions if you are not interested in the result.
You can unwrap the result to get to "throwing" behaviour:
getList({ id }).unwrap().catch(() => { How to get here });
That said, it is very likely that getList should be a query, not a mutation. Mutations are things that change data on your server.
I implemented my own way to handle access/refresh token. Basically when accessToken is expired, it awaits the dispatch of another action and, if it is successful, it dispatch again itself. The code below explains it better:
export const refresh = () => async (dispatch) => {
dispatch({
type: REFRESH_USER_FETCHING,
});
try {
const user = await api.refresh();
dispatch({
type: REFRESH_USER_SUCCESS,
payload: user,
});
return history.push("/");
} catch (err) {
const { code } = err;
if (code !== "ACCESS_TOKEN_EXPIRED") {
dispatch({
type: REFRESH_USER_ERROR,
payload: err,
});
const pathsToRedirect = ["/signup"];
const {
location: { pathname },
} = history;
const path = pathsToRedirect.includes(pathname) ? pathname : "/login";
return history.push(path);
}
try {
await dispatch(refreshToken());
return dispatch(refresh());
} catch (subErr) {
dispatch({
type: REFRESH_USER_ERROR,
payload: err,
});
return history.push("/login");
}
}
};
export const refreshToken = () => async (dispatch) => {
dispatch({
type: REFRESH_TOKEN_FETCHING,
});
try {
await api.refreshToken();
dispatch({
type: REFRESH_TOKEN_SUCCESS,
});
} catch (err) {
dispatch({
type: REFRESH_TOKEN_ERROR,
payload: err,
});
}
};
the issue is that I am finding it really difficult to test with Jest. In fact, I have implemented this test:
import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import * as actionCreators from "./actionCreators";
import * as actions from "./actions";
import api from "../../api";
jest.mock("../../api");
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe("authentication actionCreators", () => {
it("runs refresh, both token expired, should match the whole flow", async () => {
api.refresh.mockRejectedValue({
code: "ACCESS_TOKEN_EXPIRED",
message: "jwt expired",
});
api.refreshToken.mockRejectedValue({
code: "REFRESH_TOKEN_EXPIRED",
message: "jwt expired",
});
const expectedActions = [
{ type: actions.REFRESH_USER_FETCHING },
{ type: actions.REFRESH_TOKEN_FETCHING },
{ type: actions.REFRESH_TOKEN_ERROR },
{ type: actions.REFRESH_USER_ERROR },
];
const store = mockStore({ auth: {} });
await store.dispatch(actionCreators.refresh());
expect(store.getActions()).toEqual(expectedActions);
});
});
but instead of completing, the test runs indefenitely. This issue is not happening when I am testing it manually, so I think there is something missing in Jest, so my question is: is there a way to test this recursive behaviour?
Thanks
The problem is await you use with dispatch, dispatch returns an action, not a Promise, use Promise.resolve instead.
I am working on refresh token. I faced some problems with context api store. Store gives me old value.
Please look at refreshToken method there is comment explaining error. I dont't understant why if I console.log(store) React return me old value not new value.
Repeating because Stackoverlow ask me to more describe text
I am working on refresh token. I faced some problems with context api store. Store gives me old value.
Please look at refreshToken method there is comment explaining error. I dont't understant why if I console.log(store) React return me old value not new value.
import React, { useState, createContext, useEffect } from 'react';
import {MainUrl, ApiUrl} from '../config';
export const StoreContext = createContext();
export const StoreProvider = props => {
const getToken = () => localStorage.getItem("token");
const initState = () => ({
token: getToken(),
isAuth: false,
userRole: "",
userName: "",
userGroupId: null,
mainUrl: MainUrl,
apiUrl: ApiUrl,
})
const [store, setStore] = useState(initState());
const getUserInfo = async () => {
if (getToken()) {
try {
const apiConfig = {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${store.token}`,
},
};
const response = await fetch(`${store.apiUrl}get-me`, apiConfig);
const responseJson = await response.json();
if (response.ok) {
// Update Context API
setStore({
...store,
userRole: responseJson.role,
userName: responseJson.name,
userGroupId: responseJson.group_id,
isAuth: true,
})
} else if(response.status === 401) {
await refreshToken();
// Here I want call this function with refreshed token but React gives old token, although I updated token in refreshToken method
getUserInfo();
} else {
throw new Error(`Возникла ошибка во получения информации об пользователе. Ошибка сервера: ${responseJson.error}`);
}
} catch (error) {
console.log(error);
}
}
}
const logout = async (routerHistory) => {
try {
const apiConfig = {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${store.token}`,
},
};
const response = await fetch(`${store.apiUrl}logout`, apiConfig);
const responseJson = await response.json();
if (response.ok) {
// Remove token from localstorage
localStorage.removeItem("token");
// Reset Context API store
setStore(initState());
// Redirect to login page
routerHistory.push("/");
} else if(response.status === 401) {
await refreshToken();
logout(routerHistory);
} else {
throw new Error(`Возникла ошибка во время выхода. Ошибка сервера: ${responseJson.error}`);
}
} catch (error) {
console.log(error);
}
}
const refreshToken = async () => {
try {
const apiConfig = {
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": `Bearer ${store.token}`,
},
};
const response = await fetch(`${store.mainUrl}refresh-token`, apiConfig);
const responseJson = await response.json();
if (response.ok) {
// Update token in local storage
localStorage.setItem("token", responseJson.token);
// Update Context API
setStore({
...store,
userRole: 'some new role',
token: responseJson.token,
})
// Here I expect that userRole and token are changed but if I console.log(store) I get old token and null for userRole
console.log(store);
} else {
throw new Error(`Возникла ошибка во время обновления токена`);
}
} catch (error) {
throw error;
}
}
useEffect(() => {
// Get user info
getUserInfo();
}, [])
return(
<StoreContext.Provider value={[store, setStore, logout, getUserInfo]}>
{props.children}
</StoreContext.Provider>
);
}
Your setStore() function from useState() hook is an async function, hence you don't get the updated value from your console.log() call (just after the setStore()) immediately.
Also, there's no facility of providing a callback as the second argument to setStore() function, where you can log the updated state.
However, you can move your console.log(store) call inside a useEffect() hook, which triggers after every state update and ensures that you'll get the updated state.
useEffect(() => {
console.log(store);
})
So, as far as the title of your question "React Context API not updating store" is concerned, it's actually updating. It's just you are logging it before it is updated.
Hope this helps!
I'm having trouble getting the correct output from an async redux action. I am using Jest, redux-mock-adapter, and thunk as the tools.
According to redux's documentation on testing async thunks (https://redux.js.org/docs/recipes/WritingTests.html#async-action-creators), my tests should be returning an array of two actions. However, my test is only returning the first action, and not the second one that should return on a successful fetch. I think I'm just missing something small here, but it has been bothersome to say the least.
Redux Action
export const getRemoveFileMetrics = cacheKey => dispatch => {
dispatch({ type: IS_FETCHING_DELETE_METRICS });
return axios
.get("GetRemoveFileMetrics", { params: { cacheKey } })
.then(response => dispatch({ type: GET_REMOVE_FILE_METRICS, payload: response.data }))
.catch(err => err);
};
Test
it("getRemoveFileMetrics() should dispatch GET_REMOVE_FILE_METRICS on successful fetch", () => {
const store = mockStore({});
const cacheKey = "abc123doremi";
const removeFileMetrics = {
cacheKey,
duplicateFileCount: 3,
uniqueFileCount: 12,
};
const expectedActions = [
{
type: MOA.IS_FETCHING_DELETE_METRICS,
},
{
type: MOA.GET_REMOVE_FILE_METRICS,
payload: removeFileMetrics,
}
];
mockRequest.onGet(`/GetRemoveFileMetrics?cacheKey=${cacheKey}`).reply(200, removeFileMetrics);
return store.dispatch(MOA.getRemoveFileMetrics(cacheKey)).then(() => {
const returnedActions = store.getActions();
expect(returnedActions).toEqual(expectedActions);
});
});
The Output
Expected value to equal:
[{ "type": "IS_FETCHING_DELETE_METRICS" }, { "payload": { "cacheKey": "abc123doremi", "duplicateFileCount": 3, "uniqueFileCount": 12 }, "type": "GET_REMOVE_FILE_METRICS" }]
Received:
[{ "type": "IS_FETCHING_DELETE_METRICS" }]
I am using jest-fetch-mock and no axios. The following is working for me with the actions. You could refactor to async await as first step. For me it only worked that way.
I am now trying to figure out how to test the side effect (showErrorAlert(jsonResponse);). If I mock out the showErrorAlert implementation at the top of the test file (commented out in my example) then I get the same problem just like you. Actions that uses fetch won't get triggered for some reason.
export const submitTeammateInvitation = (data) => {
const config = {
//.....
};
return async (dispatch) => {
dispatch(submitTeammateInvitationRequest());
try {
const response = await fetch(inviteTeammateEndpoint, config);
const jsonResponse = await response.json();
if (!response.ok) {
showErrorAlert(jsonResponse);
dispatch(submitTeammateInvitationError(jsonResponse));
throw new Error(response.statusText);
}
dispatch(submitTeammateInvitationSuccess());
} catch (error) {
if (process.env.NODE_ENV === 'development') {
console.log('Request failed', error);
}
}
};
};
test
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
// jest.mock('../../../../_helpers/alerts', ()=> ({ showAlertError: jest.fn() }));
const middlewares = [thunk];
const createMockStore = configureMockStore(middlewares);
......
it('dispatches the correct actions on a failed fetch request', () => {
fetch.mockResponse(
JSON.stringify(error),
{ status: 500, statusText: 'Internal Server Error' }
);
const store = createMockStore({});
const expectedActions = [
{
type: 'SUBMIT_TEAMMATE_INVITATION_REQUEST',
},
{
type: 'SUBMIT_TEAMMATE_INVITATION_FAILURE',
payload: { error }
}
];
return store.dispatch(submitTeammateInvitation(data))
.then(() => {
// expect(alerts.showAlertError).toBeCalled();
expect(store.getActions()).toEqual(expectedActions);
});
});