0
votes

I have a component that uses axios to access the PubMed api (in componentDidMount), retrieves some publication ids then stores them in state as "idlist". A second function is then called (addPapers) which passes in this id list and makes a second api call to retrieve further details (title, journal, authors) for each id. All this seems to work fine and when I use react tools to check state there is an array ("paperList") full of objects that have the expected key:value pairs. However, when I try to map over this array and access the values within the objects in the render function (ie paper.title, paper.author, paper.journal) they are returning as undefined. I haven't been using react for long and suspect I am making a basic mistake but cant figure it out.

I have tried console.logging each step and the expected data is in state and correct in react tools

import axios from 'axios'
import './App.css';
import rateLimit from 'axios-rate-limit';

class App extends Component {
  state= {
    idlist: [],
    papersList : ""
  }


  componentDidMount () {
    console.log("incomponent")
     axios.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json&retmax=1000&term=((Australia%5Bad%5D)%20AND%20(%222019%2F07%2F01%22%5BDate%20-%20Publication%5D%20%3A%20%223000%22%5BDate%20-%20Publication%5D))%20AND%20(%22nature%22%5BJournal%5D%20OR%20%22Nature%20cell%20biology%22%5BJournal%5D%20OR%20%22Nature%20structural%20%26%20molecular%20biology%22%5BJournal%5D)")
    .then (response => 
      this.setState({idlist: response.data.esearchresult.idlist}, () => {
        this.addPapers(this.state.idlist)
      }
    ) 
  )}


    addPapers = (idlist) => {  
      if (idlist) {
        const http = rateLimit(axios.create(), { maxRequests: 6, perMilliseconds: 1000 }) 

        const list = this.state.idlist.map(id => {
          let paperObj ={};
          let paperList =[]
          http.get(`https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&rettype=abstract&id=${id}&api_key=9476810b14695bd14f228e63433facbf9c08`)
          .then (response2 => {
          const title = response2.data.result[id].title
          const journal = response2.data.result[id].fulljournalname
          const authorList = []
          const authors = response2.data.result[id].authors
          authors.map((author, idx) =>
            idx > 0 ? authorList.push(" " + author.name) : authorList.push(author.name))
          paperObj.title = title
          paperObj.journal = journal
          paperObj.authors = authorList.toString()
          paperList.push(paperObj) 
          })
          return paperObj
        }) 
        this.setState({papersList: list}) 
      }
    }


  render () {
    let article = ""
    if (this.state.papersList.length){
      article = this.state.papersList.map(paper =>
       console.log (paper.title)
       console.log (paper.authors)
       console.log (paper.journal)
      )
    } 

  return (
    <div className="App">
      <h1>Publications</h1>
        {article}
    </div>
  );
  }
}

export default App;

I expect that when I map over paperList and extract each paper I should be able to return the title, journal or authors using console.log(paper.title), console.log(paper.title), console.log(paper.title). These are all returning undefined.

2

2 Answers

2
votes

You have two issues in code

1) paperList array declaration should be out of map loop.

2) paperList should be returned instead of paperObj

Working code below make some enhancements in render function

Also codesandbox link

import React from "react";
import ReactDOM from "react-dom";
import rateLimit from "axios-rate-limit";
import axios from "axios";

import "./styles.css";

class App extends React.Component {
  state = {
    idlist: [],
    papersList: ""
  };

  componentDidMount() {
    console.log("incomponent");
    axios
      .get(
        "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json&retmax=1000&term=((Australia%5Bad%5D)%20AND%20(%222019%2F07%2F01%22%5BDate%20-%20Publication%5D%20%3A%20%223000%22%5BDate%20-%20Publication%5D))%20AND%20(%22nature%22%5BJournal%5D%20OR%20%22Nature%20cell%20biology%22%5BJournal%5D%20OR%20%22Nature%20structural%20%26%20molecular%20biology%22%5BJournal%5D)"
      )
      .then(response =>
        this.setState({ idlist: response.data.esearchresult.idlist }, () => {
          this.addPapers(this.state.idlist);
        })
      );
  }

  addPapers = idlist => {
    if (idlist) {
      const http = rateLimit(axios.create(), {
        maxRequests: 6,
        perMilliseconds: 1000
      });
      let paperList = [];
      this.state.idlist.forEach(id => {
        let paperObj = {};
        http
          .get(
            `https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&rettype=abstract&id=${id}&api_key=9476810b14695bd14f228e63433facbf9c08`
          )
          .then(response2 => {
            const title = response2.data.result[id].title;
            const journal = response2.data.result[id].fulljournalname;
            const authorList = [];
            const authors = response2.data.result[id].authors;
            authors.map((author, idx) =>
              idx > 0
                ? authorList.push(" " + author.name)
                : authorList.push(author.name)
            );
            paperObj.title = title;
            paperObj.journal = journal;
            paperObj.authors = authorList.toString();
            paperList.push(paperObj);
          })
          .then(result => {
            this.setState({ papersList: paperList });
          });
      });
    }
  };

  render() {
    return (
      <div className="App">
        <h1>Publications</h1>
        {this.state.papersList.length &&
          this.state.papersList.map(data => {
            return <div>{data.title}</div>;
          })}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Hope it helps!!!

0
votes

Do it like this:

render () {
let article;
if (this.state.papersList.length){
  article = this.state.papersList.map(paper => <p>span>Title is {paper.title}</span></p> )
} 



return (
    <div className="App">
      <h1>Publications</h1>
        {article}
    </div>
  );
  }