React/Redux: How to async or something else? - reactjs

Hello Everyone,
need your help today with filtering in Redux...
I have filter (you can see on a picture) with several inputs (filters) for my search.
In order to receive Fleet information (filter) I need to pass an "ID" form Client...
const clientChange = (event) => {
const client = event.target.value;
const client_id = client.id;
dispatch({ type: "CLIENT_LIST_SELECTION", payload: client_id });
getFleetFilter();
};
That's my function clientChange in Form.js
const client_id = useSelector((state) => state.client.selection);
const getFleetFilter = async () => {
dispatch({ type: "FLEET_LIST_REQUEST" });
try {
let res = await getFleet(token, client_id);
let data = res.data.data
dispatch({ type: "FLEET_LIST_LOAD", payload: data });
} catch (err) {
if (err) {
console.log("Error Fleet Data");
console.log(err);
};
};
};
That's my function getFleetFilter in Search.js
Problem: I have undefined client_id in API string, because, function getFleetFilter getting called quicker, than client_id getting stored in Redux!
Question: How can I avoid this keeping using Redux here ?
Thank you!

You can use the useEffect callback for this like so:
const client_id = useSelector((state) => state.client.selection);
useEffect(() => {
if (client_id) {
getFleetFilter();
}
}, [client_id]);
const clientChange = (event) => {
const client = event.target.value;
const client_id = client.id;
dispatch({ type: "CLIENT_LIST_SELECTION", payload: client_id });
};
const getFleetFilter = async () => {
dispatch({ type: "FLEET_LIST_REQUEST" });
try {
let res = await getFleet(token, client_id);
let data = res.data.data
dispatch({ type: "FLEET_LIST_LOAD", payload: data });
} catch (err) {
if (err) {
console.log("Error Fleet Data");
console.log(err);
};
};
};

Related

Axios get in stock items

I am trying to filter products whether it is available or not.
Not sure how to pass an axios request with ">" logic.
I've started to create an Action
export const listProductAvailable = () => async (dispatch) => {
dispatch({
type: PRODUCT_AVAILABLE_LIST_REQUEST,
});
try {
const { data } = await Axios.get(`/api/products?countInStock>0`);
dispatch({ type: PRODUCT_AVAILABLE_LIST_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: PRODUCT_AVAILABLE_LIST_FAIL, payload: error.message });
}
};
But I don't think that such a request is possible.
const { data } = await Axios.get(/api/products?countInStock>0);
Also, I don't see myself changing my Product Model creating an isAvailable boolean field as it would be redundant with countInStock =0 or not.

Fetch array of url's

I'm working with redux and I am trying to fetch Star War API.
Here is my code:
import { MOVIES_ERROR, MOVIE_CHARACTERS } from "./types";
// Get all characters
export const getCharacters = (userId) => async (dispatch) => {
try {
const res = await fetch(`https://swapi.dev/api/films/${userId}`);
if (!res.ok) {
throw new Error("sometheing went wrong");
}
const getData = await res.json();
const characters = await getData.characters;
let people = [];
Promise.all(
characters.map((url) =>
fetch(url)
.then((response) => response.json())
.then((name) => people.push(name))
)
);
dispatch({
type: MOVIE_CHARACTERS,
payload: people,
});
} catch (err) {
dispatch({
type: MOVIES_ERROR,
payload: { msg: err.response.statusText, status: err.response.status },
});
}
};
when I make a console log inside a promise. all I got people array filled with all the data, but when I dispatch it I got an empty array in the reducer. can anyone tell me what the mistake that i did?
I got the problem just now, I need to add await before Promise.all :)

Redux Action return undefined

So, I’m building an Expense App with React Native and Redux and I have this two actions:
export const getExpenses = () => async (dispatch) => {
await db.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const { description, name, value, date, type } = doc.data();
data.push({
key: doc.id,
doc, // DocumentSnapshot
description,
date,
name,
value,
type,
});
});
dispatch({
type: TYPES.GET_EXPENSES,
payload: data,
});
dispatch({
type: TYPES.SET_LOADING_EXPENSES,
payload: false,
});
console.log('getExpenses', data);
});
};
export const filterMonthInfo = () => async (dispatch, getState) => {
const info = getState().monthExpenses.data; // data returned by getExpenses()
const currentMonth = getState().dateReducer.currentDate;
const filteredInfo = info
.filter(
(data) => moment(moment(data.date).format('DD/MM/YYYY')).format('MMMM YYYY') === currentMonth,
)
.sort((a, b) => new Date(b.date) - new Date(a.date));
dispatch({
type: TYPES.GET_FILTERED_EXPENSES,
payload: filteredInfo,
});
console.log('filtermonth', filteredInfo);
};
In the Screen where I want to use the data returned by filterMonthInfo i have the following useEffect:
useEffect(() => {
getExpenses();
filterMonthInfo();
getCurrentDate();
}, []);
But since getExpenses is an async function, filterMonthInfo will run first and is going to return undefined because this last function is filtered based on data returned by getExpenses.
What is the best approach so I can make getExpenses run first and then filterMonthInfo?
Thank you
If you want to run a code after an async call is finished, you have to wait for it using Promise. write the code as
useEffect(() => {
getExpenses()
.then(()=>{
filterMonthInfo();
getCurrentDate();
}
);
}, []);
or use async await as it makes syntax more clear

How to make Async Await Function in React Native?

I want to create a function that is about uploading photo to Firebase Storage with react-native-fetch-blob. I'm using Redux and you can find action functions below:
My problem is that uploadImage function is not running like asynchronous. Firebase function is running before uploadImage, so application give me an error.
I think i can't make a asynchronous function. How can i fix it ?
uploadImage() function:
const uploadImage = async (imageSource, whereToUpload) => {
let imageURL = '';
const mime = 'image/jpg';
const { Blob } = RNFetchBlob.polyfill;
const { fs } = RNFetchBlob;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
console.log('URI =>', imageSource.uri);
let imgUri = imageSource.uri;
let uploadBlob = null;
const imageRef = firebase.storage().ref(whereToUpload + '/' + imageSource.fileName);
const uploadUri = Platform.OS === 'ios' ? imgUri.replace('file://', '') : imgUri;
await fs.readFile(uploadUri, 'base64')
.then((data) => Blob.build(data, { type: `${mime};BASE64` }))
.then((blob) => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime });
})
.then(() => {
uploadBlob.close();
// eslint-disable-next-line no-return-assign
return imageURL = imageRef.getDownloadURL();
})
.catch((error) => {
console.log(error);
});
return imageURL;
};
and the main action is:
export const addProjectGroup = (
myUser,
groupName,
groupDescription,
groupProfilePic,
) => dispatch => {
const groupProfileFinalPic = async () => {
let finalGroupPicture = { landscape: '' };
if (_.isEmpty(groupProfilePic.src)) {
await uploadImage(groupProfilePic, 'groupPictures').then((imageURL) => {
console.log('İŞLEM TAMAM!');
console.log('SELECTED IMAGE URL =>', imageURL);
finalGroupPicture.landscape = imageURL;
});
} else {
finalGroupPicture.landscape = groupProfilePic.src.landscape;
}
return finalGroupPicture;
};
console.log("final group profile pic =>", groupProfileFinalPic());
// Önce grubu yaratalım..
// eslint-disable-next-line prefer-destructuring
const key = firebase
.database()
.ref()
.child('groups')
.push().key;
firebase
.database()
.ref('/groups/' + key)
.set({
admin: {
email: myUser.email,
name: myUser.name,
uid: myUser.uid,
},
groupName,
groupDescription,
groupProfilePic: groupProfileFinalPic(),
projects: '',
})
.then(() => {
console.log('Groups oluşturuldu.');
})
.catch(e => {
Alert.alert('Hata', 'Beklenmedik bir hata meydana geldi.');
console.log(e.message);
});
dispatch({
type: ADD_PROJECT_GROUP,
});
};
You are not awaiting groupProfileFinalPic(). This should be done before creating the action you want to dispatch.
groupProfileFinalPic().then(groupProfilePic => {
return firebase
.database()
.ref("/groups/" + key)
.set({
admin: {
email: myUser.email,
name: myUser.name,
uid: myUser.uid
},
groupName,
groupDescription,
groupProfilePic,
projects: ""
})
.then(() => {
console.log("Groups oluşturuldu.");
})
.catch(e => {
Alert.alert("Hata", "Beklenmedik bir hata meydana geldi.");
console.log(e.message);
});
});
I have no clue what the last dispatch is for, you might want to do that in one of the callbacks. Your code is to verbose for an SO question, but I hope this helps anyways.
You are using both await and then on the same call. To use await, you can arrange it something like
const uploadImage = async (imageSource, whereToUpload) => {
...
try {
let data = await RNFS.fs.readFile(uploadUri, 'base64')
let uploadBlob = await Blob.build(data, { type: `${mime};BASE64` }))
...etc...
return finalResult
catch (e) {
// handle error
}
}

Firestore storing partial data to document

I have a issue with data saving to Firestore. I'm passing a list of url's to be saved to the document.
data sent in the following format
But it saving only the first data
firestore data
what may be issue? Please help.
update button click handler
handleUpdate=()=>{
const promises = [];
let files=[];
const {fileURLs,sp_License,sp_PilotsLicense}=this.state;
let err = this.validate();
if (!err) {
this.setState({ loading: true,disChecked:false })
// const Lfilename = this.state.sp_Name + '_' + new Date().getTime();
// const uploadTask = storage.ref('License/' + Lfilename).put(sp_License);
let orgFile='';
const promise1=this.uploadTaskPromise().then((res)=>{
console.log(res)
orgFile=res
});
promises.push(promise1)
console.log(orgFile)
//promises.push(this.uploadTaskPromiseMulti());
const promise2=this.uploadTaskPromiseMulti().then((res)=>{
console.log(res)
files=res
});
promises.push(promise2)
console.log(promise2)
Promise.all(promises).then(tasks => {
console.log('all uploads complete');
console.log(this.state)
if(this._mounted)
{
//this.saveData();
//console.log(orgFile.data)
this.setState({
fileURLs: files, -- here fileurls gets updated
sp_License:orgFile,
},()=>{
console.log(this.state)
this.saveData();
});
}
});
}
}
code of saveData method - I'm using react redux firebase method for saving data
saveData=()=>{
let uid = this.props.auth.uid;
let keysToRemove = ["loading", "checked", "disChecked", "open", "message",
"sp_NameError", "sp_PhoneError", "sp_emailError", 'usr_org_LicenseNumberError',
'sp_LicenseError','usr_org_StateConveredError','usr_org_DistConveredError',
'sp_NumberofEquipmentsError','sp_NumberofDronePilotsError','sp_PilotsLicense',
'sp_NumberofEquipmentsOwnedError','sp_ToolError','processingToolServiceError',
'processingToolDomainError','modalopen','EquipmentCount',
'PilotsCount','buttonName','isReady','redirect']
let newState = Object.entries({...this.state}).reduce((obj, [key, value]) => {
if(!keysToRemove.includes(key)){
obj[key] = value
}
return obj
}, {})
console.log(newState)
this.props.UpdateUserDetails(uid, newState,this.successMessage)
}
Action code
export const UpdateUserDetails= (id, droneSPDetails,func) => {
return (dispatch, getState, { getFirestore }) => {
const firestore = getFirestore()
firestore.collection('web_Users')
.doc(id)
.set({
...droneSPDetails,
sp_UpdatedOn: new Date(),
//sp_Status:"pending",
sp_ActiveFlag:"1",
},{ merge: true })
.then(() => {
func();
dispatch({ type: 'CREATE_DRONESP', droneSPDetails });
})
.catch((error) => {
console.error("Error adding document: ", error);
});
}
}

Resources