Fetching data using API in react.js - reactjs

I am trying to fetch data using API in react.js. My code is like below
import Axios from 'axios';
export const getCountry = () => dispatch => {
return Axios.get('http://treeoverflow.com/api/country/listing/true/111111111111222222222222333333333333444444444444', { crossdomain: true })
.then(response => {
console.log(response.data);
var countryData = response.data;
dispatch({
type: 'getCountries',
payload: countryData
});
})
.catch(function(error) {
console.log('hello');
dispatch({
type: 'getCountryError',
payload: error
});
});
};
export default { getCountry };
I getting below view in Network tab.
But I am not getting result. Is there any issue in this URL 'http://treeoverflow.com/api/country/listing/true/111111111111222222222222333333333333444444444444' ?

Related

Sequential Call of API in React and Redux

I need to upload multiple images but I also need to upload them one by one.
I wanted to upload them sequentially. First, you need to wait for the previous API response before calling another API response. How will I do it?
Currently is that I'm calling them in parallel. Whoever upload image API response has finished first, will be displayed.
export const uploadPhotos =
({ photos, size, controller }) =>
async (dispatch) => {
await Promise.all(
photos.forEach(async (photo, index) => {
const formData = new FormData();
formData.append("photo", photo);
dispatch({ type: constants.UPLOAD_PHOTOS_START, size });
try {
const response = await axios.post(
`${API_URL}/photos/upload`,
formData,
{
onUploadProgress({ loaded, total }) {
dispatch(setUploadProgress({ id: index, loaded, total }));
},
signal: controller.signal,
}
);
dispatch({
type: constants.UPLOAD_PHOTOS_SUCCESS,
payload: response.data,
});
} catch (error) {
dispatch({
type: constants.UPLOAD_PHOTOS_FAILURE,
payload: error,
});
}
})
);
};
export const setUploadProgress = (progress) => ({
type: constants.SET_UPLOAD_PROGRESS,
payload: progress,
});
export const resetUploadData = () => ({
type: constants.RESET_UPLOAD_DATA,
});
export const setOverallSize = (data) => ({
type: constants.SET_OVERALL_SIZE,
payload: data,
});
First: await Promise.all(photos.forEach(async () => {})) will have no effect.
forEach does not return a value so you want .map instead.
But for sequential calls, something like this is preferred:
export const uploadPhotos =
({ photos, size, controller }) =>
async (dispatch) => {
for (const [index, photos] of photos.entries()) {
const formData = new FormData();
formData.append("photo", photo);
dispatch({ type: constants.UPLOAD_PHOTOS_START, size });
try {
const response = await axios.post(
`${API_URL}/photos/upload`,
formData,
{
onUploadProgress({ loaded, total }) {
dispatch(setUploadProgress({ id: index, loaded, total }));
},
signal: controller.signal,
}
);
dispatch({
type: constants.UPLOAD_PHOTOS_SUCCESS,
payload: response.data,
});
} catch (error) {
dispatch({
type: constants.UPLOAD_PHOTOS_FAILURE,
payload: error,
});
}
}
};

How do you save/post using axios correctly

I using Spring boot has backend and react-redux has frontend. The problem is where I try too save my data to my db the first click just save my first entity out of seven. After the second click it works normal and afterwards it works normal. I have try useEffect still the same problem.
export const setChecklist = (Checklist) => {return (dispatch) => {
console.log(Checklist);
axios
.post("http://localhost:8081/api/checklist/addList", Checklist)
.then((response) => {
console.log(response);
dispatch({
type: SET_CHECKLIST,
payload: response.data,
});
})
.catch((error) => {
console.log(error);
});
};
};
try this code:
export const setChecklist = async (Checklist) => {
const response = await axios
.post("http://localhost:8081/api/checklist/addList", Checklist)
.then((response) => {
console.log(response);
dispatch({
type: SET_CHECKLIST,
payload: response.data,
});
})
.catch((error) => {
console.log(error);
});
}
useEffect(() => {
setChecklist ()
.then((res) => {
setChecklist(res)
})
.catch((e) => {
console.log(e)
})
}, [])

Async API request axios and redux freeze app in react

I'm trying to make an asynchronous request of an API.
In the meantime I am waiting for a response from it, starts preloader but at a certain moment it freeze. The request, I do it with axios and redux. What am I doing wrong?
import axios from "axios";
export const getPosts = () => {
return async (dispatch:any) => {
try {
dispatch({ type: 'GET_POSTS_BEGIN' });
const resp = await axios.get('MYAPI')
.then((resp) => {
dispatch({
type: 'GET_POSTS_SUCCESS',
posts: resp.data
})
})
} catch (err) {
console.error(err);
}
};
}

How can I mock a list of users in my redux actions?

I don't have my actual API developed yet, what would be a good way of returning a hard coded list of users in my json response?
My redux action looks like:
fetchUsers: (locationId) => {
return dispatch => {
let authToken = getItemFromStorage('authToken');
let url = API_ROOT + '/users/' + locationId + '?token=' + authToken;
axios.get(url)
.then(function(response) {
dispatch({
type: Constants.USERS_RECEIVED,
users: response.data.users,
});
});
};
Are there any good strategies of returning mock data while I develop my react frontend?
I think this is a pretty standard way of writing down an async action in Redux.
export const fetchUser = authToken => {
return async dispatch => {
dispatch({ type: "AUTH_STARTS" });
try {
const res = await axios.get(url), {
headers: {
Authorization: token
}
});
dispatch({
type: "AUTH_SUCCESS",
data: { user: res.data.user }
});
} catch (err) {
dispatch({
type: "AUTH_ERROR",
data: { error: err }
});
}
};
};
You have to handle all the cases, i.e., FETCHING, FETCHING_SUCCESS,FETCHING_ERROR
That's always considered a good practice.

Cannot read property `.then` of undefined with axios and react in actions

I am using axios in an action and trying to call that action with a chaining action. I will show what I am trying to do here:
this.props.fetchOffers().then(() => {
this.props.filter(this.props.filterOption);
});
But I get an error: Cannot read property 'then' of undefined.
What I do not get is that right below this function I have another action that is doing this exact same thing and working just fine.
this.props.sortOffers(value).then(() => {
this.props.filter(this.props.filterOption);
});
Here is a working version of this.
Here is the actions file:
import axios from 'axios';
import { reset } from 'redux-form';
import { FETCH_OFFERS, SORT_OFFERS, FETCH_OFFER, GET_FILTER, PAYMENT_TYPE } from './types';
export function paginateOffers(indexPosition, numberOfItems) {
return (dispatch) => {
axios
.get('/API/offers/pagination', {
params: {
position: indexPosition,
number: numberOfItems,
},
})
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((error) => {
console.error(error);
});
};
}
export function fetchOffers() {
return dispatch => {
axios
.get('/API/offers')
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((err) => {
console.error(err);
});
};
}
export function fetchOffer(id) {
return (dispatch) => {
axios
.get(`/API/offers/${id}`)
.then((response) => {
dispatch({ type: FETCH_OFFER, payload: response.data.result });
})
.catch((err) => {
console.error(`ERROR: ${err}`);
});
};
}
export function sortOffers(params) {
const { price, title, category, type } = params;
return dispatch =>
axios
.get('/API/offers/sort', {
params: { price, title, category, type },
})
.then((response) => {
dispatch({
type: SORT_OFFERS,
payload: response.data,
sortOptions: params,
});
dispatch({
type: PAYMENT_TYPE,
payment: type,
});
dispatch(reset('sorter'));
})
.catch((err) => {
console.error(err);
});
}
export function getFilterOption(option) {
return (dispatch) => {
dispatch({
type: GET_FILTER,
option,
});
};
}
You aren't returning a promise in your fetchOffers action creator. Notice the subtle difference in how you've declared your fat-arrow function.
Try this:
export function fetchOffers() {
return dispatch =>
axios
.get('/API/offers')
.then((response) => {
dispatch({ type: FETCH_OFFERS, payload: response.data });
})
.catch((err) => {
console.error(err);
});
}

Resources