-1

I'm trying to conditionally import a pdf file which I call const techSheet below, but for some reason when I console.log(wine.Code) it returns 3 things: undefined, correct result, correct result.

(result of console.log):

onewine.js:64 Code: undefined
onewine.js:64 Code: FGA-CHA17
onewine.js:64 Code: FGA-CHA17

Everything looks fine in state, there's only one object in this.state.wine so I can't figure out why, #1 It's returning 3 values #2 why the first one is undefined.

import React, { Component } from "react";
import API from "../utils/API";
import { Grid} from "semantic-ui-react";
import { Link } from "react-router-dom";


class OneWine extends Component {
  state = {
    wine: {}
  };

 componentDidMount() {

    API.getWine(this.props.match.params.id)
      .then(res => this.setState({ wine: res.data }))
      .catch(err => console.log(err));
  }

render() {
    const { wine } = this.state;
    const techSheet = require(`../TechSheets/Tech_${wine.Code}.pdf`);
    console.log("Code:", wine.Code)


    return (

     <a href = {techSheet} target = "_blank" rel="noopener noreferrer">
          <Button basic color="brown" target="_blank" rel="noopener noreferrer"> Tech Sheet
          </Button>
     </a>

    );
  }
}

export default OneWine;

I don't have any other console.logs or anything. Why is this coming up as undefined for the first one?

elainecadman
  • 69
  • 2
  • 8

3 Answers3

1

Generally with cases like these the log statement gets called more than once. This would be supported in your case by the fact that Render() actually gets called before ComponentDidMount() (see: http://busypeoples.github.io/post/react-component-lifecycle/).

Render then gets called twice after ComponentDidMount (and other state updates), having the right solution after the ComponentDidMount call.

lehmanad1
  • 191
  • 5
0

It has to do with how react calls the render method.

The render method is run before componentDidMount.

refer to this answer: React render() is being called before componentDidMount()

cwiswell3
  • 106
  • 4
0

Because render is called before componentDidMount() 1 time, where the state is still {wine: {}}.

React lifecycle

filipe
  • 1,957
  • 1
  • 10
  • 23