Am I doing anything wrong here ?
If I console.log value outside sync function then its getting printed, but inside async function its null
1st time Screen load = no result
2nd time if ctrl + s = getting values
const {un1} = useSelector(state => state.redusername);
const {ps1} = useSelector(state => state.redpassword);
const [user, setUser] = useState([]);
const loadowndetails = async () => {
try {
const resp = await Axios.post(
'https://example.com/owndetailshomepage.php',
{
un: un1,
un: ps1,
},
);
setUser(resp.data.phpresult);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
useEffect(() => {
loadowndetails();
}, []);
1st time Screen load = no result
2nd time if ctrl + s = getting values
Related
I want to print a document that uses data that I need to fetch first but it always gets 'undefined is not an object (evaluating 'items.username')' error since the items are still in the fetch state while the HTML variable is created
here's an example of my code
const [items, setItems] = React.useState();
const [loading, setLoading] = React.useState(true)
const getData = async () => {
const response = await axiosInstance.get(`/userData/get`)
if (response?.data?.success) {
const result = response.data?.result[0] || [];
setItems(result);
}
}
React.useEffect(() => {
(async () => {
setLoading(true);
try {
await getData();
} catch (err) {
Alert.alert("", err?.response?.data?.message || err?.message);
}
setLoading(false);
})();
}, []);
const userHTML = `<h1>${items.username}</h1>`
const printHTML = async () => {
await Print.printAsync({
userHTML,
});
};
is there a way to delay the userHTML creation so it will be generated after the fetching is done or maybe there is a best practice to do this kind of thing?
note: the print function will be on the same page as where the userData is being fetched since the data always changed so it will not be possible to fetch data and store it first then move to the page with the print function
You can set the useHTML like this:
const userHTML = `<h1>${!!items ? items.username : ''}</h1>`
I am writing my first test in Vue and using jest, the issue I am facing is my function works and I am able to console log the data and see it in the console but the wrapper data has not been updated.
async loadcsv(element=null) {
const reader = new FileReader()
let file = element[0].file
this.toggleLoading()
reader.onload = async (e) => {
try {
//Normalising headers
const results = e.target.result
let resultSplit = results.split('\n')
const header = resultSplit[0]
.toLowerCase()
.replace(/[^a-zA-Z,]/g, '')
.trim()
resultSplit[0] = header
let table = resultSplit.join('\n')
const rows = await d3.csvParse(table) //wrapper data does not update after this line, anything before reflects
await Promise.all(
rows.map(async (row) => {
this.collections.push(row)
}),
)
this.inlineVisibility = false
this.toggleLoading()
this.$refs.modal.hide()
} catch (err) {
this.toggleLoading()
this.inlineNotification('error', 'Unable to process CSV', `${err}.`)
}
}
reader.readAsText(file)
},
}
However data in the wrapper.vm.$data is still empty
collection = []
where as in the console, it shows
collection = [{my test data}]
with at mockConstructor.reader.onload
at the end
How do I get the array that shows I the console?
workingCSV is a string of my CSV file
describe('ModalAddCollectionCSV', () => {
it('Test load csv function', async () => {
const localVue = createLocalVue()
const wrapper = mount(ModalAddCollectionCSV, {
localVue,
propsData: {
visible: true,
},
})
const readAsTextMock = jest.fn()
const dataRead = jest.spyOn(global, 'FileReader').mockImplementation(function () {
const self = this
this.readAsText = readAsTextMock.mockImplementation(() => {
self.onload({ target: { result: workingCSV } })
})
})
const data = wrapper.vm.loadcsv()
expect(wrapper.vm.$data).toContain(data)
})
I am trying to developp my 1st React Native app but I am bloqued with store/fetching data from firestore.
The problem is that is dispatch before fetching all data from firestore so my filteredProfiles array is empty and my flat list in my screen is so empty too.
what should I modify? If someone could help me, i will appreciate..Thanks!!
here is my code in my screen:
ProfilesListScreen.js
const ProfilesListScreen = props => {
const connectedUser = useSelector(state => state.profiles.user);
const filteredProfiles = useSelector(state => state.profiles.filteredProfiles)
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProfiles());
}, [dispatch]);
My profilesAction.js in my store :
export const fetchProfiles= () => {
const loadedProfiles = [ ];
return async dispatch => {
await firebase.firestore().collection('users')
.get()
.then((profileSnapShot) => {
profileSnapShot.forEach((doc) => {
const firstname= doc.get("firstname");
const birth = doc.get("birth");
const age = getAge(birth.seconds);
const sex = doc.get("sex");
const newProfile= new profile(doc.id, firstname,age, "https://www.google.fr/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
loadedProfiles.push(newProfile);
});
})
dispatch({ type: SET_PROFILESLIST, profilesList: loadedProfiles } ) ;
};
and my reducer profiles.js
case SET_PROFILESLIST:
const newProfilesList = action.profilesList;
return {
filteredProfiles : newProfilesList,
};
Have a try by updating the code for fetchProfiles as below this might help you with your issue.
export const fetchProfiles= () => {
const loadedProfiles = [];
return async dispatch => {
const profileSnapShot = await firebase.firestore().collection('users').get()
profileSnapShot.forEach((doc) => {
const firstname= doc.get("firstname");
const birth = doc.get("birth");
const age = getAge(birth.seconds);
const sex = doc.get("sex");
const newProfile= new profile(doc.id, firstname,age, "https://www.google.fr/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
loadedProfiles.push(newProfile);
});
dispatch({ type: SET_PROFILESLIST, profilesList: loadedProfiles });
}
};
First I call this where result is an object
const _onSaveEvent = async (result) => {
console.log(result);
setSignature(result);
followUp();
};
Then I invoke,
const handleActualSubmission = async () => {
console.log(signature);
const { encoded, pathName } = signature;
const extension = pathName.split('.').pop();
const path = `${RNFS.DocumentDirectoryPath}/${uuidv4()}.${extension}`;
await RNFS.writeFile(path, encoded, 'base64');
stops.forEach(async (stopForPhotoConf) => {
await saveDeliveryProof(driverRoute, stopForPhotoConf, path, extension, 'signature');
});
close();
};
The resulting error is signature being null on line 1 of handleActualSubmission where const [signature, setSignature] = useState(null);
I have verifeid that the _onSaveEvent function always returns a truthy value. This issue does not appear every time this sequence of functions runs.
This code should work:
useEffect(() => {
if (signature) {
processSavedSignature();
}
}, [signature]);
It seems like the async await doesn't work in react native. When I run the code below, it just logs 'here", not the value.
class CompanyDetails extends Component {
...
componentDidMount = async () => {
await this.getCompDetailsData();
}
getCompDetailsData = async () => {
console.log('here');
await AsyncStorage.getItem('CompanyID')
.then((value) => {
console.log(value);
const compID = JSON.parse(value);
console.log(compID);
this.props.getCompDetails(propID);
});
};
...
Does anyone know why it is happening?
Thanks
Did you had 'CompanyID' stored somewhere before because if you did not store it before then it will go to the catch part which is not implemented in your case
getCompDetailsData = async () => {
console.log('here');
await AsyncStorage.getItem('CompanyID')
.then((value) => {
console.log(value);
const compID = JSON.parse(value);
console.log(compID);
this.props.getCompDetails(propID);
}).catch(error => {
console.log("CompanyID is not defined yet");
});
};
You may not have a saved value in that name "CompanyID"