Home > Enterprise >  How to display api call response in Reactjs
How to display api call response in Reactjs

Time:06-30

I am new in Reactjs and i am working with nextjs, i tried to integrate "newsletter", I created a component for this which is working fine but i am unable to display "success" or "error" message in screen/WebsitePage,i am getting "success" message in console but "success/error" message not showing Here is my code

import React, { useEffect, useState } from "react";

const Subscribe = () => {
 const [email, setEmail] = useState('');
 const [error, setError] = useState('');
 const [success, setSuccess] = useState('');

const subscribeMe = async (event) => {
            const emails = email;
            event.preventDefault();
            const res = await fetch('https://example.com/admin-panel/Api/subscribe?email=' emails);
            const { error, message } = await res.json();
            if (error) {
                    console.log(error);
                    setError(error);
            } else {
                    console.log(message);
                    setSuccess(message);
            }
};

And i put following code just below my form close,But nothing is showing in my screen,How can i do this ?

{success 
    ? 
        <span className="flex items-center text-sm font-bold text-green-700"> 
        {success}
    </span> 
    : 
<span className="flex items-center text-sm font-bold text-red-800">
{error} 
</span>

CodePudding user response:

It might be due to trying to render an object, try to JSON.stringify the data

CodePudding user response:

Actually, you have not taken the value from JSON properly. I have posted a demo code that is working exactly as you wanted.

Also, you have not used === operator for comparing string true. The status value of JSON is not in boolean it's a string.

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const subscribeMe = async (event) => {
    const res = await fetch(
      "https://mocki.io/v1/65583d53-9071-47af-b7d7-840e88763d08"
    );

    const data = await res.json();
    const error = data["status"];
    const message = data["msg"];

    if (error === "false") {
      console.log(error);
      setError(error);
    } else {
      console.log(message);
      setSuccess(message);
    }
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <span>
        {" "}
        {error} {success}
      </span>
      <br />
      <button onClick={subscribeMe}>Press me </button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Here is a demo URL https://yfv7c3.csb.app/

  • Related