How to get data from JSON with Axios? - javascript

I am trying to fetch server side data in JSON format in a table with Axios, but can't understand how to get every field like id, companyInfo etc.
json :
[
{
"id": 1,
"companyInfo": 1,
"receiptNum": 1,
"receiptSeries": "АА",
"customerName": "Mark",
"customerSurname": "Smith",
"customerMiddleName": "Jk",
"customerPhone": "0845121",
"services": [
2,
16
]
}
]
axios :
store.dispatch((dispatch) => {
dispatch({type: Actions.FETCH_DATA_START})
axios.get("http://localhost:3004/paymentReceipts")
.then((response) => {
dispatch({ type: Actions.RECEIVE_DATA, payload: response })
}).catch((err) => {
dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
})
reducer :
export const initialState = {
paymentReceipts: []
};
export default handleActions<FetchData>({
[Actions.FETCH_DATA_START]: (state, action) => {
return ;
},
[Actions.FETCH_DATA_ERROR]: (state, action) => {
return;
},
[Actions.RECEIVE_DATA]: (state, action) => {
console.log("DONE WITH STATE");
return {...state,
paymentReceipts : action.payload
}
}
}, initialState)
App
#connect(mapStateToProps, mapDispatchToProps)
export class App extends React.Component<App.Props, App.State> {
constructor() {
super();
}
render() {
console.log("CONTAINER IS ");
console.log(this.props.receiveData);
return (
<div className={style.normal}>
</div>
);
}
}
function mapStateToProps(state: RootState) {
return {
receiveData: state.receiveData
};
}
function mapDispatchToProps(dispatch) {
return {
};
}
This is what I get from console.log:
So how to get this values from JSON?

You will get all your data into response.data.
axios.get("http://localhost:3004/paymentReceipts")
.then((response) => {
dispatch({ type: Actions.RECEIVE_DATA, payload: response.data }) //Change
}).catch((err) => {
dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
})

To access a single attribute within your json-response you can simply do:
response.data.<attribute>
e.g.:
axios.get("http://localhost:3004/paymentReceipts")
.then((response) => {
dispatch({ type: Actions.RECEIVE_DATA, payload: response.data, id: response.data.id }) //Change
}).catch((err) => {
dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
})
Depending on the structure of your json and how it's formatted (e.g. array of objects) you have to iterate through it.

If you've received text instead of JSON,just like I did,
With async/await, it's simply,
let results = await axios.get("http://localhost:3004/paymentReceipts")
try {
let response = JSON.parse(results.request.response)
dispatch({ type: Actions.RECEIVE_DATA, payload: response })
} catch(err) {
dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
}

Related

GET and POST request in AXIOS

i try to post the values to the mongo server and get the values from server with same route.it is working but each and every time i need to reload the page manualy. is it right to do the POST and GET request in same route.
i try to make single page application
const createJob = async () => {
dispatch({ type: CREATE_LIST_BEGIN })
try {
const { item, price, stock } = state
await axios.post('/api/v1/list', { item, price, stock })
dispatch({ type: CREATE_LIST_SUCCESS })
dispatch({ type: CLEAR_VALUES })
} catch (error) {
if (error.response.status === 401) return
dispatch({ type: CREATE_LIST_ERROR, payload: { msg: error.response.data.msg } })
}
clearAlert()
}
const getItems = async () => {
dispatch({ type: GET_LIST_BEGIN })
try {
const { data } = await axios.get('/api/v1/list')
const { items } = data
dispatch({ type: GET_LIST_SUCCESS, payload: { items } })
} catch (error) {
console.log(error.response)
}
}
useEffect(() => {
getItems()
}, [])
The POST handler in your API should return the newly added record and createJob() should add the record to your store. So it would look something like this:
const createJob = async () => {
dispatch({ type: CREATE_LIST_BEGIN })
try {
const { item, price, stock } = state
// get the new item returned from API
const {data} = await axios.post('/api/v1/list', { item, price, stock })
// dispatch an action creator which adds the new item
dispatch({ type: ADD_LIST_ITEM, payload: { item: data.item } })
dispatch({ type: CREATE_LIST_SUCCESS })
dispatch({ type: CLEAR_VALUES })
} catch (error) {
if (error.response.status === 401) return
dispatch({ type: CREATE_LIST_ERROR, payload: { msg: error.response.data.msg } })
}
clearAlert()
}

how to write async storage value return function in react-native

how to write a method to return async storage value in react native.
I have done login authentication using Context API.
AuthContext.js
import React, { createContext } from "react";
import { useState, useEffect } from "react";
import { Alert } from "react-native";
import AsyncStorage from '#react-native-async-storage/async-storage';
import NetInfo from "#react-native-community/netinfo";
import { BASE_URL } from "../constants/Const";
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
// loading & usertoken hooks
const [isLoading, setIsLoading] = useState(false);
const [userToken, setuserToken] = useState(null);
//login method
const login = async (email, password) => {
setIsLoading(true);
//fetch method to get access token
fetch(`${BASE_URL}/sign_in`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
})
})
.then((res) => res.json())
.then((json) => {
//console.log("login auth ", json)
if (json.responseCode == 200) {
try {
setuserToken(json.responseData.access_token);
//storing usertoken value in react-native encrypted storage
AsyncStorage.setItem("userToken", json.responseData.access_token)
//console.log("user token",userToken);
}
catch (error) {
console.log("Error while saving user token data", userToken);
}
}
//showing invalid email & password alert messaqge
else {
Alert.alert('Invalid email or password.');
return;
}
})
.catch((error) => {
console.error(error);
});
setIsLoading(false);
}
//logout method
const logout = async () => {
setIsLoading(true);
//setting user token as null
setuserToken(null);
try {
//removing usertoken value in react-native encrypted storage
await AsyncStorage.removeItem("userToken");
} catch (error) {
// There was an error on the native side
console.log("Error while removing data", error);
}
setIsLoading(false);
}
// checking user is already logged in each time when app starts
const isLoggenIn = async () => {
try {
setIsLoading(true);
//let userToken = await EncryptedStorage.getItem("userToken");
let userToken = await AsyncStorage.getItem("userToken");
//console.log("accesed user token",userToken);
setuserToken(userToken);
setIsLoading(false);
} catch (error) {
console.log("Error retrieving data", error);
}
}
const [connected, setConnected] = useState(true);
useEffect(() => {
isLoggenIn();
// Subscribe
const unsubscribe = NetInfo.addEventListener(state => {
// console.log("Connection type", state.type);
// console.log("Is connected?", state.isConnected);
setConnected(state.isConnected);
});
//clean up function
return () => unsubscribe();
}, [])
return (
<AuthContext.Provider value={{ login, logout, isLoading, userToken ,connected,}}>
{children}
</AuthContext.Provider>
)
}
in Redux slice file I want access token values to make a fetch request to a server.i defined getAccessToken Method to return accessToken value but it is not returning value
DataSlice.js
import { createSlice, createAsyncThunk } from '#reduxjs/toolkit'
import { useState } from 'react';
import { Alert } from 'react-native';
import { BASE_URL } from '../constants/Const';
import AsyncStorage from '#react-native-async-storage/async-storage';
//const accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNjM2YTFlNTc4YWNlNTRjM2E5OWE4YWI2IiwiZW1haWwiOiJhZG1pbkBnbWFpbC5jb20iLCJpYXQiOjE2Njg0MDY2MzgsImV4cCI6MTY2ODQ2MDYzOH0.i_GHy2K91I0_159AIpQ4m2eFUmyXYFmF3_0sQ-o_x-w";
//user token function
const getAcessToken = async () => {
const token = await AsyncStorage.getItem('userToken');
return token;
}
var userToken = getAcessToken();
// get and delete method request options
const getDeleteRequestOptions = (methodType) => {
return {
method: methodType,
headers: {
'Content-Type': 'application/json',
'autherization': userToken
}
}
}
// save and edit method request options
const saveEditRequestOptions = (methodType, data) => {
console.log("img uri",data.imgUri)
const imgData = new FormData();
imgData.append('first_name', data.firstName);
imgData.append('last_name', data.lastName);
imgData.append('phone', data.phoneNo);
imgData.append('email', data.email);
imgData.append('image', { uri: data.imgUri, name: 'image', type: 'image/jpg' });
return {
method: methodType,
headers: {
'Content-Type': 'multipart/form-data',
'autherization': userToken
},
body: imgData
}
};
// fetch data
export const getData = createAsyncThunk('fetch', async ({pageNo,limit}) => {
return fetch(`${BASE_URL}/list_profile?page_number=${pageNo}&limit=${limit}`, getDeleteRequestOptions('GET'))
.then((response) => response.json())
.then((json) => {
//returning json receive array
if(pageNo === 0 && limit === 0){
return {data:json.receive,fetchAllData:true};
}
return {data:json.receive,fetchAllData:false};
})
.catch((error) => {
console.error(error);
});
});
// delete data
export const deleteData = createAsyncThunk('delete', async ({id}) => {
return fetch(`${BASE_URL}/delete_profile/${id}`, getDeleteRequestOptions('DELETE',userToken))
.then((res) => res.json())
.catch((error) => {
console.error(error);
});
});
// save data
export const saveData = createAsyncThunk('save', async (data) => {
return fetch(`${BASE_URL}/add_profile`, saveEditRequestOptions('POST', data))
.then((res) => res.json())
.then((json) => {
if (json.responseCode === 211) {
Alert.alert('Input Error', json.responseMessage, [
{ text: "OK" }
])
return;
}
console.log("save responese message ", json.responseMessage);
})
.catch((error) => {
console.error(error);
});
});
// edit data
export const editData = createAsyncThunk('edit', async (data) => {
return fetch(`${BASE_URL}/update_profile/${data.id}`, saveEditRequestOptions('PUT', data))
.then((res) => res.json())
.then((json) => {
console.log("edit data response message ", json.responseMessage);
})
.catch((error) => {
console.error(error);
});
});
const initialState = {
masterData: [],
filteredData: [], //array to implement search
allData:[],
imgurl: '',
};
export const dataSlice = createSlice({
name: 'crud',
initialState,
reducers: {
filterData: (state, action) => {
state.filteredData = action.payload;
},
selectedImage: (state, action) => {
state.imgurl = action.payload;
},
},
extraReducers: {
// get data
[getData.pending]: (state, action) => {
console.log('fetching data is pending');
},
[getData.fulfilled]: (state, action) => {
console.log('data fetched successfully')
if (!action.payload) {
Alert.alert('Network error', 'Data Fetching is Failded Please try Again later.', [
{ text: "OK" }
])
return;
}
console.log(action.payload.fetchAllData)
if(action.payload.fetchAllData){
//console.log("inside fetch all data")
state.allData = action.payload.data;
}
state.masterData = action.payload.data;
state.filteredData = action.payload.data;
},
[getData.rejected]: (state, action) => {
console.log('fetching request rejected');
},
// delete data
[deleteData.pending]: (state, action) => {
console.log('delete data is pending');
},
[deleteData.fulfilled]: (state, action) => {
console.log('data deleted successfully');
},
[deleteData.rejected]: (state, action) => {
console.log('data delete request rejected');
Alert.alert('Delete Data Failure', 'Deleting Data Failed. Please try Again later.', [
{ text: "OK" }
])
},
// save data
[saveData.pending]: (state, action) => {
console.log('saving data is pending');
},
[saveData.fulfilled]: (state, action) => {
console.log('data saved successfully');
},
[saveData.rejected]: (state, action) => {
console.log('data save request rejected');
Alert.alert('Data Save Failure', 'Data Save Failed. Please try Again later.', [
{ text: "OK" }
])
},
//edit data
[editData.pending]: (state, action) => {
console.log('edit data is pending');
},
[editData.fulfilled]: (state, action) => {
console.log('data edited successfully');
},
[editData.rejected]: (state, action) => {
console.log('edit data request rejected');
Alert.alert('Data Edit Failure', 'Edit data Failed. Please try Again later.', [
{ text: "OK" }
])
},
},
})
// Action creators are generated for each case reducer function
export const { filterData, selectedImage } = dataSlice.actions;
export default dataSlice.reducer
i want to get access token values
The reason is that you are not calling getAccessToken() with await like this:
var userToken = await getAcessToken();
since it is asynchronous function.

Deleting a user is returning nothing in the backend

I'm trying to delete an user, but the req.body in the backend is an empty object.
In the backend I have the following code:
const deleteUser = async (req, res) => {
console.log(req.body);
console.log(req.config);
const user = await User.findById(req.body.userId);
if (user) {
const deleteUser = await user.remove();
res.send({ message: "User Deleted", user: deleteUser });
} else {
res.status(404).send({ message: "User Not Found" });
}
};
Here the console log is an empty object, I must that the other functions work perfectly.
In the frontend, I'm using redux, I think I'm doing something wrong in the actions, but I can't find out what, I will post all my code for reference.
action.js:
export const deleteUser = (userId) => async (dispatch, getState) => {
dispatch({ type: USER_DELETE_REQUEST, payload: userId });
try {
const { data } = await Axios.delete(
"http://localhost:3030/v1/user/userProfile/deleteUser",
{
userId: userId,
}
);
dispatch({ type: USER_DELETE_SUCCESS, payload: data });
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
dispatch({ type: USER_DELETE_FAIL, payload: message });
}
};
In the reducer:
export const userDeleteReducer = (state = {}, action) => {
switch (action.type) {
case USER_DELETE_REQUEST:
return { loading: true };
case USER_DELETE_SUCCESS:
return { loading: false, success: true };
case USER_DELETE_FAIL:
return { loading: false, error: action.payload };
default:
return state;
}
};
And I'm calling the action like that:
const userSignin = useSelector((state) => state.userSignin);
const { userInfo, loading, error } = userSignin;
<button
onClick={() => {
console.log(userInfo._id);
dispatch(deleteUser(userInfo._id));
props.onClose();
}}
className='deleteAccountModalButton'
>
Delete account!
</button>
I tried everything, but I can't find where the problem, can somebody tell me why the req.body is empty in the backend?
EDIT:
I managed to make it work by modifying the order of parameters in actions:
export const deleteUser = (userId) => async (dispatch, getState) => {
dispatch({ type: USER_DELETE_REQUEST, payload: userId });
const {
userSignin: { userInfo },
} = getState();
try {
const { data } = await Axios.delete(
"http://localhost:3030/v1/user/userProfile/deleteUser",
{
data: {
headers: { Authorization: `Bearer ${userInfo.token}` },
userId,
},
}
);
dispatch({ type: USER_DELETE_SUCCESS, payload: data });
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
dispatch({ type: USER_DELETE_FAIL, payload: message });
}
};
I will leave this here in case somebody else will have this problem.

React-Failed to load resource: the server responded with a status of 400 (Bad Request)

I am making a blog app. Where if I try to access the individual profiles the spinner keeps running, but the data is there when I check in the react dev tools. Where did I go wrong? Everything else was working fine. The profiles are visible, but when I get inside the individual profile is where the problem happens
Profile.js
import React, { Fragment, useEffect } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Spinner from "../layout/Spinner";
import { getProfileById } from "../../actions/profile";
import { Link } from "react-router-dom";
const Profile = ({ getProfileById, profile: { profile }, auth, match }) => {
useEffect(() => {
getProfileById(match.params.id);
}, [getProfileById, match.params.id]);
return (
<Fragment>
{profile === null ? (
<Spinner />
) : (
<Fragment>
<Link to='/profiles' className='btn btn-light'>
Back to Profiles
</Link>
{auth.isAuthenticated &&
auth.loading === false &&
auth.user._id === profile.user._id && (
<Link to='/edit-profile' className='btn btn-dark'>
Edit Profile
</Link>
)}
</Fragment>
)}
</Fragment>
);
};
Profile.propTypes = {
getProfileById: PropTypes.func.isRequired,
profile: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
profile: state.profile,
auth: state.auth,
});
export default connect(mapStateToProps, { getProfileById })(Profile);
The source from which the data is comming, profile.js
import axios from "axios";
import { setAlert } from "./alert";
import {
GET_PROFILE,
PROFILE_ERROR,
UPDATE_PROFILE,
ACCOUNT_DELETED,
CLEAR_PROFILE,
GET_PROFILES,
GET_REPOS,
} from "./types";
export const getCurrentProfile = () => async (dispatch) => {
try {
const res = await axios.get("/api/profile/me");
dispatch({
type: GET_PROFILE,
payload: res.data,
});
} catch (error) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
//Get all profiles
export const getProfiles = () => async (dispatch) => {
dispatch({ type: CLEAR_PROFILE });
try {
const res = await axios.get("/api/profile");
dispatch({
type: GET_PROFILES,
payload: res.data,
});
} catch (error) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
//Get Profile by id
export const getProfileById = (userId) => async (dispatch) => {
try {
const res = await axios.get(`/api/profile/user/${userId}`);
dispatch({
type: GET_PROFILES,
payload: res.data,
});
} catch (error) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
//Get github repos
export const getGithubRepos = (username) => async (dispatch) => {
try {
const res = await axios.get(`/api/profile/github/${username}`);
dispatch({
type: GET_REPOS,
payload: res.data,
});
} catch (error) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
//Create or Update profile
export const createProfile =
(formData, history, edit = false) =>
async (dispatch) => {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const res = await axios.post("/api/profile", formData, config);
dispatch({
type: GET_PROFILE,
payload: res.data,
});
dispatch(setAlert(edit ? "Profile Updated" : "Profile Created"));
if (!edit) {
history.push("/dashboard");
}
} catch (error) {
const errors = error.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
//Add experience
export const addExperience = (formData, history) => async (dispatch) => {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const res = await axios.put("/api/profile/experience", formData, config);
dispatch({
type: UPDATE_PROFILE,
payload: res.data,
});
dispatch(setAlert("Experience Added", "success"));
history.push("/dashboard");
} catch (error) {
const errors = error.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
//Add Education
export const addEducation = (formData, history) => async (dispatch) => {
try {
const res = await axios.put("/api/profile/education", formData);
dispatch({
type: UPDATE_PROFILE,
payload: res.data,
});
dispatch(setAlert("Education Added", "success"));
history.push("/dashboard");
} catch (error) {
const errors = error.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
// Delete experience
export const deleteExperience = (id) => async (dispatch) => {
try {
const res = await axios.delete(`/api/profile/experience/${id}`);
dispatch({
type: UPDATE_PROFILE,
payload: res.data,
});
dispatch(setAlert("Experience Deleted", "success"));
} catch (error) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
// Delete education
export const deleteEducation = (id) => async (dispatch) => {
try {
const res = await axios.delete(`/api/profile/education/${id}`);
dispatch({
type: UPDATE_PROFILE,
payload: res.data,
});
dispatch(setAlert("Education Deleted", "success"));
} catch (error) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
//Delete account & profile
export const deleteAccount = () => async (dispatch) => {
if (
window.confirm("Are you sure? This will be permanently delete the account!")
)
try {
await axios.delete(`/api/profile`);
dispatch({
type: CLEAR_PROFILE,
});
dispatch({
type: ACCOUNT_DELETED,
});
dispatch(setAlert("Account Removed"));
} catch (error) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
My github repo Link
Your actions expect a dispatch function as the second function's parameter. But you aren't providing it anywhere.
Considering how your actions are written this should resolve the issue:
const dispatch = useDispatch();
useEffect(() => {
getProfileById(match.params.id)(dispatch);
}, [dispatch, getProfileById, match.params.id]);
Also, you are providing getProfileById as the component property and you have it as an import on top of the file.
It worked.
There was some error in the getProfilebyID function.
under src -> components -> profile.js
at the bottom you did define mapStateToProps, however you never created the function mapDispatch which is used to grab the data from your thunk call getProfileById
here is more info:
ctrl + find -> mapDispatchToProps
https://react-redux.js.org/api/connect

Passing loaded user ID into my action for update User Data (MERN ReactJS + Express)

I'm trying to update my user profile data from the client-side. The user has to upload a file and the component will catch the actual user-loaded ID, store it into a state, and then use this state to find the user in the database to update the value I need. But I can't figure out how to pass the state to filter the user; in the way you see below the It gives me a PUT: http://localhost:3000/api/users/upgrade/undefined 404 (Not Found). Someone could help me?
Here's my server router:
//SERVER ROUTER
router.put("/upgrade/:id", upgrade.single("userPlus_doc"), (req, res) => {
User.findById(req.params.id)
.then((user) => {
user.userPlus = true;
user.userPlus_doc = req.file.originalname;
user
.save()
.then(() => res.json("User Upgraded!"))
.catch((err) => res.status(404).json({ success: false }));
})
.catch((err) => res.status(404).json({ success: false }));
});
My action and reducer:
//ACTION
export const upgradeUser = (formData, id) => (dispatch, getState) => {
axios
.put(`/api/users/upgrade/${id}`, formData, tokenConfig(getState))
.then((res) =>
dispatch({
type: USER_UPGRADE,
payload: res.data,
})
)
.catch((err) =>
dispatch(returnErrors(err.response.data, err.response.status))
);
};
export const setUserUpgradeID = (user_id) => (dispatch) => {
dispatch({
type: SET_USER_UPGRADE_ID,
payload: user_id,
});
};
//REDUCER
const initialState = {
user_id: "",
};
export default function foo(state = initialState, action) {
switch (action.type) {
...
case SET_USER_UPGRADE_ID:
return {
...state,
user_id: action.payload,
};
case USER_UPGRADE:
return {
...state,
user: state.user.filter((user) => user._id !== action.payload),
};
default:
return state;
}
}
And how I pass the information client-side:
class ProfileUpgrade extends Component {
state = {
userPlus_doc: "",
user_id: "",
};
onFileChange = (e) => {
this.setState({
userPlus_doc: e.target.files[0],
});
this.props.setUserUpgradeID({
user_id: this.props.auth.user._id,
});
};
/* onChange = () => {
this.props.setUserUpgradeID({
user_id: this.props.auth.user._id,
});
console.log(this.props.setUserUpgradeID);
};
*/
onSubmit = (e, user_id) => {
e.preventDefault();
const formData = new FormData();
/* formData.append("userPlus", this.state.userPlus); */
formData.append("userPlus_doc", this.state.userPlus_doc);
this.props.upgradeUser(formData, this.props.user_id);
};
render() {
return ( ... )
}
}
ProfileUpgrade.propTypes = {
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
user: state.user,
auth: state.auth,
user_id: state.user_id,
});
export default connect(mapStateToProps, { upgradeUser, setUserUpgradeID })(
ProfileUpgrade
);
The only things I need from the client-side are the doc title and the user ID to update the correct user object. To update the boolean userPlus I set the backend to set the value to true and save it.
Am I missing something in my action to make the component pass filter the user ID?

Categories

Resources