Is there away to make a popup do a request to display extra information - reactjs

I am trying to make an information board that when user press for more information, it will do a get /:id to the backend where it will grab the data and display it in the popup

You can do something like:
const onClickHandler= async () => {
const res = await fetch(endpoint);
const data = await res.json();
setData(data)
}
But using try catch and the rest of things to validate a successful req.

Related

How to fix error 429 in React using sync function or disk-cache?

I am coming across a 429 error while fetching a lot of urls at the same time, in useEffect. I am trying to fetch prices of stocks by mapping the names from the array shortNames using a proxy server called allorigins
The function that fetches the data:
const fetchData = async (url) => {
try {
const response = await fetch(url)
if (!response.ok) throw response.statusText
const data = response.json()
return data
} catch (error) {
console.error(error)
}
};
The price_response stores the price data in an array after the Promises are resolved:
const price_response = await Promise.all(shortNames.map((stock) =>
fetchData(`https://api.allorigins.win/raw?url=https://query1.finance.yahoo.com/v8/finance/chart/${stock}.BO`)
));
This async method of fetching throws error when it loads the first time. Refreshing the page adds more data to price_response retrieving some already fetched data from the disk-cache.
I am trying to find a better way, as to not make the user refresh the page again and again.
Is there a way I can fetch 60-70 urls using async or even sync function? Also, can I use disk-cache in a more customised way to make this work on the very first load?

Firebase Storage async request with "listAll" method. React

I'm getting an image from a user and storing it with in Cloud Storage through Firebase. The storing works fine.
Right after that I'm requesting all images from the storage to display them, but I got the response without the last submit. So I need to refresh the page, then useEffect make one more request and everything works.
UPD. Here's the the complete logic:
This function is uploading image to the storage:
const uploadImage = async (image,imageName) => {
if (image == null) return;
const imageRef = ref(storage,`images/${imageName}`);
try {
uploadBytes(imageRef, image);
} catch (err) {
alert(`${err}`)
}
}
This function does request to firestore, but doesn't return last uploaded image every time, just randomly. sometimes it does, usually not :
const getImages = async () => {
try {
const imagesListData = await listAll(imagesListRef);
setImagesList([]);
imagesListData.items.forEach(item => {
getDownloadURL(item).then(url => setImagesList(prev => [...prev,url]));
})
} catch(err){
alert(err.message);
}
}
after refreshing the page, useEffect does the job :
useEffect(() => {
getImages();
},[])
As I said above sometimes it works as I expected from the first try without me changing the code(which is the most confusing),most of the times I need to refresh the page to get the last image.
p.s. list() instead listAll() give same results

Cant receive data from gitHub API

I try to receive data from gitHub API. As the name is entered in input element I send a request to
https://api.github.com/search/users?q=${username} in:login type:user.
And I`m expecting that I received all users with this username (input element may has whole username or just a part of username). But got only one user.
You can use async and await method to get your proper result.
const gitUsers = async (username) => {
const response = await fetch(`https://api.github.com/search/users?q=${username}`);
const result = await response.json();
console.log(result);
};
gitUsers("carl")

How to set data to the state after fetching from backend?

I want to get data from the backend and want to set those data to the state in ReactJS. Here is my source code
const [eachAsset, setEachAsset] = useState([]);
function ShowModalView(id)
{
axios.get("http://localhost:8070/assets/detail/"+id).then((res)=>{
const data = res.data
setEachAsset(data)
//console.log(eachAsset);
}).catch((err)=>{
console.log(err.message);
})
setShow2(true);
}
When I uncomment the console log, it shows an empty array. It means, setEachAsset(data) does not work properly. But I want to store data that are getting from the backend to the eachAsset state. What is the problem of this source code?
setEachAsset([...data])
I hope this would work
I would recommend using async-await which makes the code easier to read and understand the flow of the program as compared to promise chains.
const [eachAsset, setEachAsset] = useState([]);
const ShowModalView = async (id) => {
try {
const resp = await axios.get("http://localhost:8070/assets/detail/"+id);
setEachAsset(resp.data)
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
setShow2(true);
}

How to refresh child component from parent component

I have a page that allows the user to upload and display a photo. The backend API is all built out. My problem is after I successfully upload the photo, I need to refresh the page in order to see the new photo at the bottom of the page. Here's the relevant code:
Parent Component
refreshPage = (value) => {
if(this.state.photoUploaded)
{
//this refreshes the API call to get the new photo
this.componentDidMount();
}
};
async componentDidMount(){
const url = <the url of my API>;
const response = await fetch(url);
const data = await response.json();
this.setState({eventdata:data});
var i = 0;
for(i = 0; i < data.photos.length; i++)
{
this.state.photos.push({"url":data.photos[i].url});
}
this.setState({loading:false});
}
render(){
<div>
<PhotoSelectorComponent eventdata={this.state.eventdata} refreshPage={this.refreshPage}></PhotoSelectorComponent>
<PhotoDisplayComponent photos={this.state.photos} eventdata={this.state.eventdata} refreshPage={this.refreshPage}></PhotoDisplayComponent>
</div>
}
I have the PhotoSelectorComponent notifying the Parent Component when a Photo has been uploaded. It calls the RefreshPage function, which calls componentDidMount(), which makes the api call an additional time, and I see the new photo in my photos array. I'm not even sure if this is the best way to do this, but it's an idea that I tried based on what I've read, and it's working. But I'm not sure how to re-render the PhotoDisplayComponent at this point. I'm updating the state, but it's not refreshing the page. I'm very close to making this work, but I'm not sure if they way that I have it setup currently is best practice or not. I feel like the page should just refresh itself if I have everything wired correctly.
You have some basic React mistakes there, like directly mutating state and calling setState few times in the same function. Try this:
async componentDidMount() {
const url = 'someurl';
const response = await fetch(url);
const data = await response.json();
const newPhotos = data.photos.map((photo) => {
return { "url": photo.url }
})
this.setState(({
loading: false,
photos:[...this.state.photos,...newPhotos],//I dont think you actually get only new photos, but following your code...
eventdata: data
}));
}
Also i think your architecture doesn't make much sense, because i've never seen a direct call to componentDidMount.

Resources