How do make sure getData() runs before MovieCard function?

I’ve been making a simple random movie generator app with react js and material ui but I’ve been having trouble with async functions. From what I understand, data isn’t grabbed from the API fast enough to provide it to the component I made. How do I correct this? Is there a way to make sure I grab the data before showing it? Also, how do I display an image link as an image on react? Any help would be great. Thanks!

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { Grid } from '@material-ui/core';
import BTTF from "./BTTF.jpg";
import ratings from "./ratings.csv"

var movie;
var plot;

async function getData(){
  const response = await fetch(ratings);
  const movieData = await response.text();
  
  const table = movieData.split('\n').slice(1);
  const movieChoice = table[Math.floor(Math.random() * 171)];

  const columns = movieChoice.split(',');
  const id = columns[0];

  const url = `http://www.omdbapi.com/?i=${id}&apikey=d3852437`;
  const poster = `http://img.omdbapi.com/?i=${id}&apikey=d3852437`;
  
  const responseAPI = await fetch(url);
  const APIData = await responseAPI.json();
  movie = APIData.Title;
  plot = APIData.Plot;

  console.log(APIData);
  
  console.log(`URL: ${url} + ${poster}\n Movie: ${movie}\n Plot: ${plot}`);

  


}

getData();


const MovieCard = () =>{

    
    const useStyles = makeStyles({
        root: {
            width: 300,
        },
        media: {
            height: 435,
        },
    });

    const classes = useStyles();

    return <Grid container justify="center" alignItems="center" direction="column">
      <Card className={classes.root}>
      <CardActionArea>
        <CardMedia
          className={classes.media}
          image={BTTF}
          title={movie}
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            {getData.movie}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {plot}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions style={{justifyContent: 'center'}}>
        <CardActions >
          <Button variant="outlined" color="secondary">Generate</Button>
        </CardActions>
      </CardActions>
    </Card>
    </Grid>
    
}

export default MovieCard;

18 thoughts on “How do make sure getData() runs before MovieCard function?”

  1. For First Question

    useEffect ( () => {
    async function getData(){
      const response = await fetch(ratings);
      const movieData = await response.text();
      
      const table = movieData.split('\n').slice(1);
      const movieChoice = table[Math.floor(Math.random() * 171)];
    
      const columns = movieChoice.split(',');
      const id = columns[0];
    
      const url = `http://www.omdbapi.com/?i=${id}&apikey=d3852437`;
      const poster = `http://img.omdbapi.com/?i=${id}&apikey=d3852437`;
      
      const responseAPI = await fetch(url);
      const APIData = await responseAPI.json();
      movie = APIData.Title;
      plot = APIData.Plot;
    
      console.log(APIData);
      
      console.log(`URL: ${url} + ${poster}\n Movie: ${movie}\n Plot: ${plot}`);
    }
    
    getData();
    }, [])
    

    For Second Question

    {poster && <img src={poster} />}
    
    Reply

Leave a Comment