简体   繁体   中英

ReactJS save output of a fetch to a var?

it's me again, I'm still working on my collection projet with a ReactJS frontend and NodeJS backend.

Today I'm trying to add a function "onClick" where I set a new array of urlImages.

In order to do that, I must save the value output of my fetch in a variable called "obj", so I can use it again in another fetch. The point of doing that is when I click into an image of the collection, it sets a new array of urlimages which will get the url's of the image which belongs to the collection.

It shouldn't be that hard but I'm having trouble doing that.. can anyone help me ?

 import React from 'react'; import { render } from 'react-dom'; import Gallery from 'react-photo-gallery'; import Photo from './Photo'; class PhotoGallery extends React.Component { constructor(props){ super(props); this.onClick = this.onClick.bind(this); this.state = { urlImages: [], nomCollection: [] }; } async componentDidMount() { const response = await fetch("http://localhost:3004/getUrlImages"); const newList = await response.json(); this.setState(previousState => ({ ...previousState, urlImages: newList, })); } galleryPhotos() { if(this.state.urlImages) { return this.state.urlImages.map(function(urlimage) { return { src: urlimage.urlimage, width: 2, height: 2 } }) } } async onClick(event) { const rawObj = await fetch("http://localhost:3004/getCollectionFromUrlImage?urlimage="+event.target.src); const obj = await rawObj.json(); const response = await fetch("http://localhost:3004/getUrlImagesFromCollection?collection="+obj[0].nom); const newList = await response.json(); this.setState(previousState => ({ ...previousState, urlImages: newList, })); } render() { return ( <Gallery axis={"xy"} photos={this.galleryPhotos()} onClick={this.onClick}/> ) } } const photos = []; export default PhotoGallery; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

The response of my json is :

[{"nom":"Cartes"}]

The console.log shows :

0: {nom: "Cartes"}

length: 1

__proto__: Array(0)

BUUT the alert(obj) shows undefined .

Any help? I want the obj to be equal to "Cartes"..

Thanks in advance guys :)

You need to await the first fetch, as you've done with the second:

const rawObj = await fetch("http://localhost:3004/getCollectionFromUrlImage?urlimage="+event.target.src);
const obj = await rawObj.json();

The second fetch in your onClick method is running before your server has had a chance to respond to the first fetch, because you don't await it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM