I am new to react-redux,when I was developing an express app in which I choose react as my frontend and redux store concept.
I need to pass the logged in user as a param in my axios.get method How can i do this?
What I have been doing is getting the user._id from database and using it but this approach is tedious and will not work for a number of users
componentDidMount(){
const url="http://localhost:5000/api/users/viewFarm/5d3ac84a86688123789e13b2";
fetch (url,{
method: "GET"
}).then(response=> response.json()).then(result=>{
console.log(result);
this.setState({
farmList : result
});
});
}
I can see in Redux Dev Tool the SET_CURRENT_USER is displaying the logged in user but is there any other way so that I can pass this user.id in the axios.get method while doing ComponentDidMount(). 1. My react-redux have authActions
//Json Generator
export const registerJson = (userData, history) => dispatch => {
axios
.post("/api/users/registerJson/5d3ac84a86688123789e13b2/5d42d171e7ceef2a90245470/5d44256d8b3cf92af46e2c9b", userData)
.then(res => history.push("/JsonGenerator"))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
.
.
.
.
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded
};
};
import { SET_CURRENT_USER, USER_LOADING } from "../actions/types";
const isEmpty = require("is-empty");
const initialState = {
isAuthenticated: false,
user: {},
loading: false
};
export default function(state = initialState, action) {
switch (action.type) {
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: !isEmpty(action.payload),
user: action.payload
};
case USER_LOADING:
return {
...state,
loading: true
};
default:
return state;
}
}
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
Redux dev tool o/p
{
auth:{
isAuthenticated:false=>true}
user:{
exp:1604591134,
iat:1573034208,
id:"5d36f73f67665a1740620f55",
name:"Pritam Kumar",
},
}
}
In the URL, you can append as a query parameter
You can use query strings.
componentDidMount(){
const data = this.state.data //i put state data for example you can use any data source
const url=`http://localhost:5000/api/users/viewFarm/?userId=${data._id}`;
fetch (url,{
method: "GET"
}).then(response=> response.json()).then(result=>{
console.log(result);
this.setState({
farmList : result
});
});
}
and in your nodejs app
app.get('/api/users/viewFarm/', (req,res)=>{
//you can use router instead of app
console.log(req.query.userId)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.