Ben J
Ben J

Reputation: 147

Receive JSON content of Fetch API Post call

I am new to React and I have a chat UI in which I am trying to test an API call from a service. Please assume that the call itself have the correct parameters, and even if not I want to see the error JSON response and I am just getting a blank message in the chat as a response to the user message. The call working through Postman app in chrome but when trying to assign the call result to var in react it doesn't present the JSON response value when trying to post the message through the UI chat.

This is the function, the user message transfered to this function and then an answer should appear right after via the fetched API request:

submitMessage(e) {
    e.preventDefault();

    var s = fetch('https://***', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': '****',
        },
        body: JSON.stringify({ inputText: 'hi' })
    });

    this.setState({
        chats: this.state.chats.concat([
            {
                username: "newUser",
                content: <p>{ReactDOM.findDOMNode(this.refs.msg).value}</p>
            },
            {
                username: "responsePlace",
                content: s
            }
        ])
    });
}

Upvotes: 1

Views: 1723

Answers (1)

Chriss Hd
Chriss Hd

Reputation: 643

fetch is a javascript Promise therefore it needs to be resolved using then

fetch(...) .then(response => response.json()) // resolves json content of the response .then(data => console.log(data)) // your actual data as a javascript object .catch(ex => console.log(ex)) // exception handler in case anything goes wrong in the fetch

More on fetch api: fetch api examples

More on Promises: Promises

Upvotes: 1

Related Questions