0

I have a hard time to call fetch() from a small React app.

The idea is to

  1. have a class (so I can reuse it)
  2. call fetch to get json-data from the server
  3. 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

Omar Dieh
  • 500
  • 3
  • 8
user2902165
  • 303
  • 2
  • 14
  • Maybe try using life cycles? like [componentWillMount()](https://www.pluralsight.com/guides/how-to-use-componentwillmount) – Baha Aug 07 '22 at 18:17

1 Answers1

0

fetch is a async function. So the callback you define in then method is executed whenever the promise that fetch returns is fulfilled and successful. Javascript does not wait for your async function to finish and runs rest of the code, executes alert. If you want Javascript to wait for the response, use an async function and await to wait for the request response. You can learn more by reading about async functions, promises, await in Javascript.

c0m1t
  • 1,089
  • 1
  • 7
  • 16