Mich
Mich

Reputation: 322

ReactJS save output of a fetch to a var?

It's me again, I'm still working on my collection project 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)

BUT the alert(obj) shows undefined.

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

Upvotes: 0

Views: 150

Answers (1)

UncleDave
UncleDave

Reputation: 7188

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.

Upvotes: 1

Related Questions