How to make this into a function - reactjs

I have this redux hook. I will essentially be creating fetchStudents for student, district, school, etc. Instead of rewriting this code, I essentially want to be able to pass in the URL and the type. How can I do this?
import fetch from 'isomorphic-fetch';
import { createAction } from 'utils/actionUtils';
import * as types from './StudentConstants';
export const setLoading = createAction(types.SET_LOADING);
const getStudents = students => ({
type: types.SET_STUDENTS,
payload: students,
});
export const fetchStudents = (students) => {
return (dispatch) => {
return fetch('http://gsndev.com/gsndb/student/', {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `JWT ${localStorage.token}`,
},
})
.then(response => response.json())
.then((s) => {
dispatch(getStudents(s));
})
.catch(error => (error));
};
};

fetchStudents is normal function. So pass any arguments you want and use these arguments for branching logic.
For example
export const fetchStudents = (type, url) => {
return (dispatch) => {
return fetch(url, { // Here you may put url
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `JWT ${localStorage.token}`,
},
})
.then(response => response.json())
.then((s) => {
switch (type) {
case 'students':
dispatch(getStudents(s));
break;
case 'district':
dispatch(getDistricts(s)); // There can be action creator for districts
break;
// And so on for other types
}
})
.catch(error => (error));
};
};

Related

converting custom react function to async

I made this custom hook.
import axios from "axios";
import Cookies from "js-cookie";
import React from "react";
const useGetConferList= () => {
let token = JSON.parse(localStorage.getItem("AuthToken"));
const Idperson = JSON.parse(Cookies.get("user")).IdPerson;
const [response, setResponse] = React.useState();
const fetchConfer= (datePrensence, idInsurance, timePrensence) => {
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
.then((r) => {
setResponse(r.data.Data);
})
.catch(() => alert("NetworkError"));
};
return { fetchConfer, response };
};
export default useGetConferList;
as you can see I export the fetchConfer function. but I want to make it async. for example, calling the function and then doing something else like this:
fetchConfer(Date, Time, Id).then((r) => {
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
});
as you can see in non async situation, I can't use then.
You can try this
const fetchConfer = async (datePrensence, idInsurance, timePrensence) => {
try {
const response = await axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
setResponse(response.data.Data);
// need to return data
return response.data.Data
} catch(error) {
alert("NetworkError")
}
};
use the function in another async function
const someAsyncFunc = async () => {
// try catch
const r = fetchConfer(Date, Time, Id)
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
...
or use it how you are currently using it
Hope it helps

REDUX - how to store ARRAY id's when i do a dispatch loop?

I need to save the ID's that I am receiving when fetching in a loop in the store but I am not realizing how to iterate the object
This is my action's
export function uploadImage(files) {
return function async(dispatch) {
const myHeaders = new Headers();
myHeaders.append("Authorization", `Token ${localStorage.getItem('***')}`)
for(let i = 0; i < files.length; i++) {
const formdata = new FormData();
formdata?.append("image", files[i], files[i].name);
fetch(`${process.env.REACT_APP_URL_API}/api/images/`, {
'method': "POST",
'headers': myHeaders,
'body': formdata,
'redirect': 'follow'
})
.then(resp => resp.json())
.then(json => dispatch(activeImage(json.id)))
}
}
}
export const activeImage = ( id ) => ({
type: "PUSH_ID_IMAGE",
payload: id
});
My reducer:
case "PUSH_ID_IMAGE":
return{
...state,
images: [...action.payload]
}
Redux actions don't support async actions by defualt, you could try using redux-thunk
It allows you to return a function as an action and gives you access to dispatch and getState so you can dispatch events to your reducer from within the function as well as being able to retrieve the state
After installing redux-thunk you could write something like this as your action:
const uploadImage = files => {
return async (dispatch, getState) => {
// ... your proccessing / loop here
// ... inside the loop
const response = await fetch(`${process.env.REACT_APP_URL_API}/api/images/`, {
'method': "POST",
'headers': myHeaders,
'body': formdata,
'redirect': 'follow'
})
.then(resp => resp.json())
dispatch({
type: "PUSH_ID_IMAGE",
payload: response
}) // send the data returned from "resp.json"
}
}

Unhandled Rejection (TypeError): Cannot read property 'error' of undefined

I'm fairly new to React and I've been trying to create a SignUp page, however, I'm stuck in this error. Can someone give me any indication on what I should do in order to solve this error?
Signup Method:
// = Action =
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
}
Rewrite Signup method (ps: I only changed the .catch handler)
`
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err =>
console.log(err));
return err;
}
`
You need to wrap up your fetch logic inside a Promise to return a value to the caller.
export const signup = user => {
return new Promise((resolve, reject) => {
fetch(`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(jsonData => resolve(jsonData))
.catch(err => resolve({error: `something went wrong err : ${err}`}));
})
}
signup(user).then(data => {
if (data.error) {
// handle error case
} else {
// handle success case
}
})
Now your signup method will return a value. Your data variable won't be undefined anymore.
I hope it helps, feel free to add comments or ask me more details

How to synchronize fetch method in redux action

I am wondering how I can sync my fetch method. I want to prevent rendering data in a component before a response is returned.
Here is my redux action with my fetch method:
export const FETCH_DATA_START = 'FETCH_DATA_START'
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS'
export const FETCH_DATA_FAILED = 'FETCH_DATA_FAILED'
export const getData = () => {
return (dispatch) => {
dispatch({
type: FETCH_DATA_START
})
fetch(baseUrl, {
credentials: "include",
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then((res) => {
dispatch({
type: FETCH_DATA_SUCCESS,
payload: res
})
})
.catch((err) => {
console.log(err)
dispatch({
type: FETCH_DATA_FAILED,
payload: 'error'
})
})
}
}
A common practice in this case is to set a flag like isFetching to true, and then display a loading spinner in your JSX based on the status of this flag.
Then when you received data, you hide this spinner and show the data.

Unable to get response using fetch in React

I am trying to call 3rd party API, to fetch some data. I am getting the response in Postman, but not getting expected response when I execute my code.
I tried in 2 ways. Both ways I am getting "Promise pending".What could be the reason??
//request.js
Method 1
export const callSearchGiftsAPI = inputs => dispatch => {
dispatch(searchGifts());
let url = new URL(GIFT_SEARCH_API_URL),
params = {
apiKey: GIFT_SEARCH_API_KEY,
query: inputs.item,
country: 'us',
itemsPerPage: 3
};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
return new Promise((resolve, reject) => {
setTimeout(() => resolve(
fetch(url, {
method: 'GET',
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
Authorization: `secret ${SECRET}`
}
})
.then(res => {
if (!res.ok) {
return Promise.reject(res.statusText);
}
console.log("hi", res.json());
return res.json();
})
.then(gifts => dispatch(searchGiftsSuccess(gifts)))
.catch(err => dispatch(searchGiftsError(err)))), 500)
});
}
Method 2:
export const callSearchGiftsAPI = inputs => dispatch => {
dispatch(searchGifts());
let url = new URL(GIFT_SEARCH_API_URL),
params = {
apiKey: GIFT_SEARCH_API_KEY,
query: inputs.item,
country: 'us',
itemsPerPage: 3
};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
fetch(url, {
method: 'GET',
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
Authorization: `secret ${SECRET}`
}
})
.then(res => {
if (!res.ok) {
return Promise.reject(res.statusText);
}
console.log('result', res.json());
return res.json();
})
.then(gifts => dispatch(searchGiftsSuccess(gifts)))
.catch(err => dispatch(searchGiftsError(err)));
};
//form.js
class Form extend React.Component{
onSubmit(values) {
const inputs = Object.assign({}, values);
return this.props.dispatch(callSearchGiftsAPI(inputs));
}
//Remaining code
}
Also please note that I have installed CORS plugin in Chrome, to allow the request.If I disable it and add mode:'no-cors' I am getting as 401 unauthorized.What else am I supposed to do?
What happens is that you are creating a new Promise and returning it, but you are not waiting for it to resolve. You can either use then of the new async/await syntax to get the correct result :
onSubmit = async values => {
const inputs = Object.assign({}, values);
return await this.props.dispatch(callSearchGiftsAPI(inputs));
}
The code above will work with your first method.
Since your second method does not return anything, you will never get your result, you need to return your fetch's result and apply the code I gave above :
return fetch(url, {
This worked.
I was trying to put console.log in the wrong place and hence was not able to see the response properly.
export const callSearchGiftsAPI = inputs => dispatch => {
dispatch(searchGifts());
let url = new URL(GIFT_SEARCH_API_URL),
params = {
apiKey: GIFT_SEARCH_API_KEY,
query: inputs.item,
country: 'us',
itemsPerPage: 3
};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
console.log(url);
return fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `secret ${SECRET}`
}
})
.then(res => {
console.log('result');
return res.json();
})
.then(response => {
console.log(response); // changed
dispatch(searchGiftsSuccess(response.items));
})
.catch(err => dispatch(searchGiftsError(err)));

Resources