ssjack
ssjack

Reputation: 47

How to pass data from Fetch API to index.html

I am trying to pass data from an API to my website.

My directory:

project > server.js | public

public > index.html | styles.css

My code, a part of it, in server.js:

var link, txt; // I want to export these 2 variables to the website

fetch(`url`)
    .then(res => res.json())
    .then(body => {
     console.log(body); //receiving a json body and assigning data to both variables
     link = body.path;
     txt = body.path;
    })
    .catch(error => {
      console.log(error);
});

I did not find any way to manipulate this into index.html, any good advice? is this possible through React and Node?

In App.js from React, I wanted something like:

<p>{link} or {text}</p>

I'm new in web dev, any help you can give would be greatly appreciated.

Upvotes: 0

Views: 1280

Answers (2)

ssjack
ssjack

Reputation: 47

For people from the future, found a way to do this with React (https://reactjs.org/) and Node express (https://nodejs.org/en/). Don't know if this is the best way, but it worked for me:

import React,{useState,useEffect} from 'react';
import './App.css';

function App() {
  
  const [data,setData]=useState([]);

  const [data1,setData1]=useState([]);

  const [data2,setData2]=useState([]);


  const getData=()=>{
        fetch(`url`)
        
        .then(function(response){
            console.log(response);
            return response.json();
        })

        .then(body => {
             console.log(body);
             setData(body.path); 
             setData1(body.path);  
             setData2(body.path);  
        })

        }

  useEffect(()=>{
             getData()
   },[])

  
  return (

    <div className="App">
    
      <p>{data}</p>
      
      <p>{data1}</p>

      <p>{data2}</p>

      </a>

    </div>

  );

}

export default App;

Upvotes: 0

vanshaj
vanshaj

Reputation: 549

This would be easier in react, but it's also possible to do it in plain HTML. You can fetch the data on the frontend and manipulate the required <p> node using DOM APIs like document.getElementById and changing the inner html when your fetch promise is resolved

Upvotes: 2

Related Questions