K
K
kashcheev2020-05-03 02:56:00
React
kashcheev, 2020-05-03 02:56:00

Is it possible to output xml-js output in componentDidMount?

Hello!

Please tell me how to "make friends" two designs:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    }
  }

componentDidMount() {
    const url = "";
    fetch(url)
    .then(response => response.json())
    .then(json => this.setState({ posts: json }))
  }

  render() {
    const { posts } = this.state;
    return (
      <div className="container">
        {posts.map((post) => (
          <div className="card" key={post.id}>
              #{post.id} {post.title}
              <p className="text">{post.body}</p>
          </div>
        ))}
      </div>
    );
  }
}


var convert = require('xml-js');
var xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
'    <title>Happy</title>' +
'    <todo>Work</todo>' +
'    <todo>Play</todo>' +
'</note>';
var result1 = convert.xml2json(xml, {compact: true, spaces: 4});
var result2 = convert.xml2json(xml, {compact: false, spaces: 4});
window.alert(result1, '\n', result2);


Is it possible to put the exhaust inside componentDidMount() instead of the url value where the json reference is now? ps React picking out of interest, experience with JS is small. Google is an excellent mentor, but I did not find specific examples of the situation. pss The solution is interesting using js tools, it is clear that most often there is a normal json on hand. result1, '\n', result2




Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Alexandrovich, 2020-05-05
@kashcheev

componentDidMount() {
    const result1 = convert.xml2json(xml, { compact: true, spaces: 4 });
    const data =  JSON.parse(result1);
    this.setState({ posts: data })
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question