0

I am trying to obtain and display data in a React app from the samhsa.org API. I am able to console.log an XML string though I cannot seem get the node values. I have exhausted the last week trying to figure this out. Forgive me, I am learning React and not experienced with XML. When I run:

import React from 'react';
import axios from 'axios';
import PropTypes from 'prop-types';
import { parser, parseString } from 'xml2js';


function ResourcesGrid(props) {
  return (
    <div>
      <ul className='resources-list'>
        {props.resources.map((resource) => {
          return (
            <li key={resource.title} className='resource-item'>
              <ul className='space-list-items'>
                <li>{resource.description}</li>

              </ul>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

ResourcesGrid.propTypes = {
  resources: PropTypes.array.isRequired
}

export default class Resources extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    }
  }
  componentDidMount () {
    let xml = 'http://content.samhsa.gov/ext/api/items?q-taxo=PanicDisorders~Recovery';
      return axios.get(xml)
    .then(function (res) {
      console.log(res.data);
      return res.data;
    });
    this.setState = {
      resources: resources
    }
  }
  render() {
    return (
      <div>
      {!this.state.resources
        ? <p>LOADING...</p>
        : <ResourcesGrid resources={this.state.resources} />
      }`enter code here`
      </div>
    )
  }
}

I get an object an object that contains a XML string:

An object that contains a XML string

When I log res.data I get a string. I can't figure out how to get to the next level (EX: res.data["description"]).

I have tried 'xml2js':

componentDidMount () {
    let xml = 'http://content.samhsa.gov/ext/api/items?q-taxo=PanicDisorders~Recovery';
      return axios.get(xml)
    .then(function (res) {
      parser.parseString(res, function(err,result){
        resData = result['data'];
        console.log(resData);
      });
      return resData;
    });
    this.setState = {
      resources: resources
    }
  }

and get TypeError: Cannot read property 'parseString' of undefined:

TypeError: Cannot read property 'parseString' of undefined

I've tried to convert it to JSON as well. Am I way off? I need help!

Jon Saw
  • 7,599
  • 6
  • 48
  • 57
danlauby
  • 45
  • 1
  • 6

0 Answers0