GET and POST request in AXIOS - javascript

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()
}

Related

Firebase TypeError: Cannot read properties of null (reading 'indexOf')

When I console.log(docSnap) I'm getting a firebase error, see in the below image. I have tried all the solutions but none of them worked.
useEffect(() => {
if (folderId === null) {
dispatch({
type: "UPDATE_FOLDER",
payload: { folder: ROOT_FOLDER }
})
}
// otherwise fetch from database
const getdocSnap = async () => {
const docRef = doc(db, "folders", folderId);
return await getDoc(docRef);
}
const docSnap = getdocSnap();
console.log(docSnap);
if (docSnap.exists()) {
dispatch({
type: "UPDATE_FOLDER",
payload: { folder: { id: docSnap.id, ...docSnap.data() } }
})
} else {
console.log("No such document!");
dispatch({
type: "UPDATE_FOLDER",
payload: { folder: ROOT_FOLDER }
})
}
}, [folderId])
How the problem solved ?
Ans: Created an async function callFunc & pasted all my logic inside it & called it.
Try the code below
useEffect(() => {
if (folderId === null) {
return dispatch({
type: "UPDATE_FOLDER",
payload: { folder: ROOT_FOLDER }
})
}
// otherwise fetch from database
const callFunc = async () => {
const docRef = doc(db, "folders", folderId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
dispatch({
type: "UPDATE_FOLDER",
payload: { folder: { id: docSnap.id, ...docSnap.data() } }
})
} else {
console.log("No such document!");
dispatch({
type: "UPDATE_FOLDER",
payload: { folder: ROOT_FOLDER }
})
}
}
callFunc();
}, [folderId])

Req.body from the database is returning empty object when trying to delete user

I'm trying to delete an user, but the problem is that I'm trying to do that by taking the user id from the req.body in the database, I have the following logic in the redux actions and I think here is a problem with the order of the params:
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",
{
userId
},
{
headers: { Authorization: `Bearer ${userInfo.token}` },
});
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 });
}
};
When I'm doing console logging the req.body in the backend is empty, what can I do?

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

this.props.history.push does not redirect on first attempt

We are trying to redirect to a search results page once we have our results. We are using axios.get() to send the get request which follows:
export const searchPosts = (type, query) => async dispatch => {
dispatch({ type: PARTIAL_LOADING, payload: false });
const res = await axios.get('/api/search/',
{
params: {
type: type,
query: query
}});
dispatch({ type: PARTIAL_LOADING, payload: true });
dispatch({
type: SEARCH,
payload: res.data
});
};
We are trying to redirect to the next page using the following:
async submitSearch(values) {
const type = values.type ? values.type : "Default";
const query = values.query;
if (type && query)
{
await this.props.searchPosts(type, query)
.then(_ => {
this.props.history.push('/search_results');
});
}
}
This redirects after the first attempt but will always fail the first time.

How to get data from JSON with Axios?

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})
}

Categories

Resources