POST request response undefined , but REQUEST works - javascript

userSlice
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
import LoginService from "../../Services/Login.service";
export const userRegister = createAsyncThunk(
"users/register",
async (params) => {
try {
const { registerForm } = params;
const { data } = await LoginService.register(registerForm);
return data;
} catch (error) {
}
}
);
const initialState = {
userData: {},
errorResponse: null,
status: "idle",
};
export const userSlice = createSlice({
name: "User",
initialState,
reducers: {},
extraReducers: {
[userRegister.pending]: (state, action) => {
state.status = "loading";
},
[userRegister.fulfilled]: (state, action) => {
state.status = "succeeded";
state.userData = action.payload;
},
[userRegister.error]: (state, action) => {
state.status = "failed";
state.errorResponse = action.payload;
},
},
});
export default userSlice.reducer;
Login.service.js
import axios from "axios";
const API = axios.create({ baseURL: 'http://localhost:3001'});
const LoginService = {
register: async (registerData ) => {
await API.post('/users/register', registerData)
}
};
export default LoginService;
Hi.I try add register feature to my app. But when i submit register form, the datas is saved to the database without any problems. But this line const data = await LoginService.register(registerForm); doesnt work data is undefined but when i same post request in postman i get response data the way i want.

LoginService.register is not returning anything,
you can fix that by doing:
const LoginService = {
register: async (registerData ) => {
const response = await API.post('/users/register', registerData);
return response.data;
}
};

Related

Redux toolkit fullfilled even there is an error and showing the error message from django showing in fullfilled case

Fullfilled and update the state perfectly. But When use wrong credential, the detailed error from django showing in the fullfilled "userInfo" state. If we catch the error through rejectWithValue, the message is just
"code 401"
userSlice.js
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
import axios from "axios";
export const login = createAsyncThunk(
"USER_LOGIN_REQUEST",
async (cred, thunkAPI) => {
try {
console.log("this is one thig");
console.log("username: ", cred.username, "password: ", cred.password);
const config = {
headers: {
"Content-type": "application/json",
},
};
const { data } = await axios.post(
"/api/users/login/",
{ username: cred.username, password: cred.password },
config
);
localStorage.setItem("userInfo", JSON.stringify(data));
return data;
} catch (error) {
return thunkAPI.rejectWithValue(error);
}
}
);
const userInfoFromStorage = localStorage.getItem("userInfo")
? JSON.parse(localStorage.getItem("userInfo"))
: null;
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
};
const userSlice = createSlice({
name: "userRegister",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(login.pending, (state = {}, action) => {
return { loading: true, userInfo: [] };
})
.addCase(login.fulfilled, (state = {}, action) => {
return { loading: false, userInfo: action.payload };
})
.addCase(login.rejected, (state = {}, action) => {
return { loading: false, error: action.payload.message };
});
},
});
export default userSlice.reducer;
store.js
const store = configureStore({
reducer: {
userLogin: userLoginReducer,
cart: cartReducer,
productList: productListReducer,
productDetails: productDetailsReducer,
},
// initialState,
middleware,
});
login.jsx
const { error, loading, userInfo } = userLogin;
const submitHandler = (e) => {
e.preventDefault();
dispatch(login({ username: email, password }));
};
I was expected error message form django on rejected case not in fullfilled case.

Why State won't Change When I try to dispatch in getServerSideProps? Redux-Next-Wrapper

When I Try to dispatch in getServerSideProps the Redux Store won't change
When i Console.log the store After Dispatch I see the changes in console but when the page load the Store is empty array..
Why Changes won't effect?
createSlice
import { createSlice } from "#reduxjs/toolkit";
import { Store } from "../../types/type";
const { actions, reducer } = createSlice({
name: "dashboard",
initialState: { users: [], roles: [], ads: [], category: [] },
reducers: {
SET_ROLES: (store, { payload }) => {
store.roles = payload;
return store;
},
SET_USERS: (store, { payload }) => {
store.users = payload;
return store;
},
SET_ADS: (store, { payload }) => {
store.ads = payload;
return store;
},
SET_CATEGORY: (store, { payload }) => {
store.category = payload;
return store;
},
},
});
// Selector
export const selectDashboard = (store: Store) => store.entities.dashboard;
export const { SET_ROLES, SET_ADS, SET_USERS, SET_CATEGORY } = actions;
export default reducer;
Page
export const getServerSideProps = wrapper.getServerSideProps(
(store) => async (context) => {
const { data: ads } = await axios.get(endPoint);
const { data: users } = await axios.get(endPoint);
const { data: roles } = await axios.get(endPoint);
const { data: categories } = await axios.get(endPoint);
console.log("Before DISPATCH", store.getState());
store.dispatch(SET_USERS(users));
store.dispatch(SET_ADS(ads));
store.dispatch(SET_CATEGORY(categories));
store.dispatch(SET_ROLES(roles));
console.log("After DISPATCH", store.getState()); // I Can See The Changes In Console
return {
props: {},
};
}
);
The state set in the server will get cleared when dehydrations happen. You need to update server state with client state.
const reducer = (
state: ReturnType<typeof combinedReducer> | undefined,
action: AnyAction
) => {
if (action.type === HYDRATE) {
const nextState = {
...state, // use previous state
...action.payload, // apply delta from hydration
};
return nextState;
} else {
return combinedReducer(state, action);
}
};
export const store = configureStore({
reducer,
devTools: process.env.NODE_ENV !== 'production',
middleware: (getDefaultMiddleware) =>
....

SQLite not working with Redux in React Native

After introducing Redux to my React Native Expo app, whenever I try to interact with the database my app stops working.
actions.js:
export const SET_SELECTED_PLAYERS = "SET_SELECTED_PLAYERS"
export const SET_PLAYERS = "SET_PLAYERS"
export const SET_SELECTED_COURSE = "SET_SELECTED_COURSE"
export const SET_COURSES = "SET_COURSES"
//Player actions
export const setPlayers = (players) => (
{ type: SET_PLAYERS, payload: players, }
)
export const setSelectedPlayers = (players) => (
({ type: SET_SELECTED_PLAYERS, payload: players, })
)
export const setSelectedCourse = (course) =>
({ type: SET_SELECTED_COURSE, payload: course, })
export const setCourses = (courses) =>
({ type: SET_COURSES, payload: courses, })
reducers.js:
import { SET_PLAYERS, SET_SELECTED_PLAYERS, SET_SELECTED_COURSE, SET_COURSES } from "./actions"
const initialState = {
players: [],
selectedPlayers: [],
courses: [],
selectedCourse: null,
round: {}
}
export const playerReducer = (state = initialState, action) => {
switch (action.type) {
case SET_PLAYERS:
return { ...state, players: action.payload }
case SET_SELECTED_PLAYERS:
return { ...state, selectedPlayers: action.payload }
default:
return state
}
}
export const courseReducer = (state = initialState, action) => {
switch (action.type) {
case SET_SELECTED_COURSE:
return { ...state, selectedCourse: action.payload }
case SET_COURSES:
return { ...state, courses: action.payload }
default:
return state
}
}
store.js:
import { createStore, combineReducers, applyMiddleware } from "redux";
import { courseReducer, playerReducer } from "./reducers";
const rootReducer = combineReducers({ playerReducer, courseReducer })
export const Store = createStore(rootReducer)
SQLite used in component :
const dispatch = useDispatch()
const db = SQLite.openDatabase("players.db")
useEffect(() => {
db.transaction(tx => {
tx.executeSql("SELECT * FROM Player", [], (trans, result) => {
dispatch(setPlayers(result.rows._array))
})
})
}, [])
Table for Player exists and app worked before I introduced Redux. It interacts with Firebase and when fetching data from cloud Redux has no problems. What problems could it have with SQLite?
Use sqlite query in redux action
export const getUsers = () => {
try {
return async dispatch => {
const result = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const json = await result.json();
if (json) {
dispatch({
type: GET_USERS,
payload: json
})
} else {
console.log('fetch user api error');
}
}
} catch (error) {
console.log('action error');
}
}

Error Type: undefined is not an object (evaluating '_useSelector.attendance')

I'm having a challenge with redux as I keep getting this error: TypeError: undefined is not an object (evaluating '_useSelector.attendance'). Everything seems to be working fine but I just done understand why it keeps coming back to this even when it seems the code is okay to my knowledge
Reducers.js
import { GET_ATTENDANCE, ADD_TO_ATTENDANCE_LIST } from "./actions";
const initialState = () => ({
attendance: [],
attendancebook: [],
});
function attendanceReducer(state = initialState, action) {
switch (action.type) {
case GET_ATTENDANCE:
return { ...state, attendance: action.payload };
case ADD_TO_ATTENDANCE_LIST:
return {
...state,
attendancebook: [...state.attendancebook, action.payload],
};
default:
return state;
}
}
export default attendanceReducer;
AttendanceScreen.js
function AttendanceScreen({ route }) {
const navigation = useNavigation();
const listing = route.params;
const dispatch = useDispatch();
const { attendance, attendancebook } = useSelector(
(state) => state.attendanceReducer
);
const getAttendance = () => {
try {
dispatch({
type: GET_ATTENDANCE,
payload: attendancelist,
});
} catch (error) {
console.log(error);
}
};
const fetchAttendance = () => dispatch(getAttendance());
const addToAttendanceList = (data) => dispatch(addAttendance(data));
useEffect(() => {
fetchAttendance();
}, []);
store.js
import attendanceReducer from "./reducers";
const persistConfig = {
key: "root",
storage: AsyncStorage,
whitelist: ["attendancebook"],
};
const rootReducer = combineReducers({
attendanceReducer: persistReducer(persistConfig, attendanceReducer),
});
export const store = createStore(rootReducer, applyMiddleware(thunk));
export const persistor = persistStore(store);
actions.js
export const GET_ATTENDANCE = "GET_ATTENDANCE";
export const ADD_TO_ATTENDANCE_LIST = "ADD_TO_ATTENDANCE_LIST";
export const addAttendance = (data) => (dispatch) => {
dispatch({
type: ADD_TO_ATTENDANCE_LIST,
payload: data,
});
};
Please any help will be appreciated.

Redux Toolkit and Axios

I'm using Redux Toolkit to connect to an API with Axios.
I'm using the following code:
const products = createSlice({
name: "products",
initialState: {
products[]
},
reducers: {
reducer2: state => {
axios
.get('myurl')
.then(response => {
//console.log(response.data.products);
state.products.concat(response.data.products);
})
}
}
});
axios is connecting to the API because the commented line to print to the console is showing me the data. However, the state.products.concat(response.data.products); is throwing the following error:
TypeError: Cannot perform 'get' on a proxy that has been revoked
Is there any way to fix this problem?
I would prefer to use createAsyncThunk for API Data with extraReducers
Let assume this page name is productSlice.js
import { createSlice,createSelector,PayloadAction,createAsyncThunk,} from "#reduxjs/toolkit";
export const fetchProducts = createAsyncThunk(
"products/fetchProducts", async (_, thunkAPI) => {
try {
//const response = await fetch(`url`); //where you want to fetch data
//Your Axios code part.
const response = await axios.get(`url`);//where you want to fetch data
return await response.json();
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message });
}
});
const productsSlice = createSlice({
name: "products",
initialState: {
products: [],
loading: "idle",
error: "",
},
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchProducts.pending, (state) => {
state. products = [];
state.loading = "loading";
});
builder.addCase(
fetchProducts.fulfilled, (state, { payload }) => {
state. products = payload;
state.loading = "loaded";
});
builder.addCase(
fetchProducts.rejected,(state, action) => {
state.loading = "error";
state.error = action.error.message;
});
}
});
export const selectProducts = createSelector(
(state) => ({
products: state.products,
loading: state.products.loading,
}), (state) => state
);
export default productsSlice;
In your store.js add productsSlice: productsSlice.reducer in out store reducer.
Then for using in component add those code ... I'm also prefer to use hook
import { useSelector, useDispatch } from "react-redux";
import {
fetchProducts,
selectProducts,
} from "path/productSlice.js";
Then Last part calling those method inside your competent like this
const dispatch = useDispatch();
const { products } = useSelector(selectProducts);
React.useEffect(() => {
dispatch(fetchProducts());
}, [dispatch]);
And Finally, you can access data as products in your component.
It is happening because your reducer function is not a pure function, it should not be having any asynchronous calls.
something like this should work. it will fix the error you are getting
const products = createSlice({
name: "products",
initialState: {
products: []
},
reducers: {
reducer2: (state, { payload }) => {
return { products: [...state.products, ...payload]}
})
}
}
});
and api should be called outside
const fetchProducts = () => {
axios.get('myurl')
.then(response => {
//console.log(response.data.products);
store.dispatch(products.actions.reducer2(response.data.products))
})
};
PS: haven't tried running above code, you may have to make modifications as per your need.

Categories