Fetch decode execute

Process me these fetch, decode and execute api in single form and give me coding in React.jsx

------------------------------------

import React, { useState } from 'react';

const FetchDecodeExecute = () => {
  const [inputUrl, setInputUrl] = useState('');
  const [rawData, setRawData] = useState('');
  const [decodedData, setDecodedData] = useState('');
  const [executedResult, setExecutedResult] = useState('');

  // Decode Base64 or JWT
  const decode = (data) => {
    try {
      if (data.includes('.') && data.split('.').length === 3) {
        // JWT Decode
        const base64Url = data.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(
          atob(base64)
            .split('')
            .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
            .join('')
        );
        return jsonPayload;
      } else {
        // Base64 Decode
        return atob(data);
      }
    } catch (e) {
      return 'Decoding failed: Invalid format';
    }
  };

  // Simulate Execute
  const execute = (decoded) => {
    try {
      const json = JSON.parse(decoded);
      return `Executed Function with data: ${JSON.stringify(json)}`;
    } catch {
      return `Executed as plain string: ${decoded}`;
    }
  };

  const handleProcess = async () => {
    setRawData('');
    setDecodedData('');
    setExecutedResult('');

    try {
      const response = await fetch(inputUrl);
      const result = await response.text(); // assuming base64 or jwt string
      setRawData(result);

      const decoded = decode(result);
      setDecodedData(decoded);

      const executed = execute(decoded);
      setExecutedResult(executed);
    } catch (error) {
      setRawData('Fetch failed: ' + error.message);
    }
  };

  return (
    <div className="p-6 max-w-2xl mx-auto">
      <h1 className="text-2xl font-bold mb-4">Fetch → Decode → Execute API</h1>
      <input
        type="text"
        placeholder="Enter API URL"
        value={inputUrl}
        onChange={(e) => setInputUrl(e.target.value)}
        className="w-full border p-2 mb-4"
      />
      <button
        onClick={handleProcess}
        className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
      >
        Run Process
      </button>

      <div className="mt-6">
        <h2 className="font-semibold">Raw Fetched Data:</h2>
        <pre className="bg-gray-100 p-2">{rawData}</pre>

        <h2 className="font-semibold mt-4">Decoded Data:</h2>
        <pre className="bg-gray-100 p-2">{decodedData}</pre>

        <h2 className="font-semibold mt-4">Executed Result:</h2>
        <pre className="bg-gray-100 p-2">{executedResult}</pre>
      </div>
    </div>
  );
};

export default FetchDecodeExecute;

Comments

Popular posts from this blog

Petroleum