I have a hard time to call fetch()
from a small React
app.
The idea is to
- have a
class
(so I can reuse it) - call
fetch
to getjson-data
from the server - populate it with the data fetched from a server.
The class
looks like:
import React from 'react';
class GetJsonData extends React.Component {
constructor(props) {
super(props);
this.state = {
id: this.props.id,
content: this.props.content
};
}
render() {
return <h2>Id: {this.state.id + ' content: ' + this.state.content} </h2>
;
}
}
export default GetJsonData;
The index.js looks like:
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import GetJsonData from './GetJsonData'
var jsonString = '{\n'+
'"id":"1",\n'+
'"content":"Returning Weblogic JSON 2022-08-07 08:56:34"\n'+
'}';
const data = JSON.parse(jsonString)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<GetJsonData id={data.id} content={data.content} />);
I have tried to add a function to index.js
but in some how I can not return the string
from the server I have for eg tried the following:
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import GetJsonData from './GetJsonData'
var jsonString = '{\n'+
'"id":"1",\n'+
'"content":"Returning Weblogic JSON 2022-08-07 08:56:34"\n'+
'}';
jsonString = getJson();
const data = JSON.parse(jsonString)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<GetJsonData id={data.id} content={data.content} />);
function getJson() {
var retvalue;
const API = 'http://127.0.1.1:7001/weblogic-rest-facade/resources/rest-facade/get-json';
fetch(API)
.then((data) => data.json())
.then((json) => {
retvalue = JSON.stringify(json);
alert('retvalue_1: ' + retvalue);
})
alert('retvalue_2: ' + retvalue);
return retvalue;
}
It seems like the alert with 'retvalue_2: ' always executes first, to me that is very strange.
So if you guys got any clue how to get the json-string
before it is needed for render please let me know.
Best regards
Fredrik