I am new to reactjs and expressjs. How do I get the data from reactjs and store it in a variable.
So far I am able to do res.send the data.
app.get('*', (req, res) => {
const data = {hello: world};
res.send(data);
});
This sends the data to the browser and displays but I want to just save the data to a variable instead of displaying it.
This is React.js example
import axios from 'axios'
click () {
axios.get('yourAPIAdress')
.then(response => console.log(response))
}
and this is your node.js example code;
const https = require('https');
https.get('yourAPIAdress', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
You can in your React Component do something like:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(){
super();
this.state ={users: []};
}
componentDidMount() {
fetch('/users')
.then(users => {
console.log(users);
this.setState({ users })
});
}
render() {
return (
<div className="App">
<h1>Users</h1>
{this.state.users.map(user =>
<div key={user.id}>user: {user.name} Password: {user.password}</div>
)}
</div>
);
}
}
export default App;
Assuming the object you're interested in called "users"
(* You need to change your JSX according to your object fields for sure, to test this)
Related
I'm completely new to JS and React and im trying to upload a file with my MS custom teams app.
I've found the information i need to make it work, i just dont understand how i can use it within my teams tab.
import React from 'react';
import './App.css';
import * as microsoftTeams from "#microsoft/teams-js";
class Tab extends React.Component {
constructor(props){
super(props)
this.state = {
context: {}
}
}
componentDidMount() {
new Promise((resolve) => {
microsoftTeams.getContext(resolve);
})
.then((context) => {
this.setState({ context });
//var inputs {}
const queryParameters = new URLSearchParams({ function: "getDocuments", input: '"'+ context.userPrincipalName + '"',});
console.log(`userPrincipalName is '${context.Id}'`);
console.log(`teamName is '${context.teamName}'`);
console.log(`http://localhost/openims/json.php?${queryParameters}`);
return fetch(`http://localhost/openims/json.php?${queryParameters}`);
})
.then((res) => res.json())
.then((result) => this.setState({ ...result }))
.catch((error) => this.setState({ error }))
.finally(() => this.setState({ isLoaded: true }));
}
render() {
const { error, isLoaded, name, age, city } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
<li>
{/* Your Link */}
{name} {age} {city}
</li>
</ul>
);
}
}
}
export default Tab;
Currently im using a componentDidMount to fetch some info i need from a URL, but now i need to figure out how i add another componentDidMount(i think) to do a PUT and upload a file to my drive location. Preferably the drive location of my MS teams team onedrive.
So somewhere i have to put this:
PUT /me/drive/root:/FolderA/FileB.txt:/content
Content-Type: text/plain
The contents of the file goes here.
So i can actually upload a file. How do i go about this?
You can not add multiple componentDidMount() methods however in success callback you can call another API to upload the file.
Or you can call after promise in same componentDidMount() method.
Also you can write your code like below:
fetch('https://me/drive/root:/FolderA/FileB.txt:/', {
method: 'PUT',
body: fileContent
})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
})
.catch((error) => {
console.error('Error:', error);
});
You can refer below documentation:
https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http#example-upload-a-new-file
Similar issue reference URL:
How do I upload a file with the JS fetch API?
I am trying currently trying to create a CRUD Contacts Application using react. I'm currently having a problem on pulling user details through my database. Here is my code:
import React, { Fragment, useEffect } from "react";
import { useParams } from "react-router-dom";
const ContactDetails = () => {
const params = useParams();
const { contactId } = params;
useEffect(() => {
fetch(
`https://MY-DB.firebaseio.com/contacts/${contactId}.json`
)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
}, [contactId]);
return (
<Fragment>
<h1>CONTACT DETAIL</h1>
<p>{params.contactId}</p>
</Fragment>
);
};
export default ContactDetails;
But trying to log the data results in null.
Here is my database:
Database
Any help is appreciated.
Beginner here.
Trying to fetch some data from a server and display it in my react component once its fetched.
However, I am having trouble integrating the async function into my react component.
import React, { useState } from "react";
import { request } from "graphql-request";
async function fetchData() {
const endpoint = "https://localhost:3090/graphql"
const query = `
query getItems($id: ID) {
item(id: $id) {
title
}
}
`;
const variables = {
id: "123123123"
};
const data = await request(endpoint, query, variables);
// console.log(JSON.stringify(data, undefined, 2));
return data;
}
const TestingGraphQL = () => {
const data = fetchData().catch((error) => console.error(error));
return (
<div>
{data.item.title}
</div>
);
};
export default TestingGraphQL;
I'd like to simply show a spinner or something while waiting, but I tried this & it seems because a promise is returned I cannot do this.
Here you would need to use the useEffect hook to call the API.
The data returned from the API, I am storing here in a state, as well as a loading state to indicate when the call is being made.
Follow along the comments added in between the code below -
CODE
import React, { useState, useEffect } from "react"; // importing useEffect here
import Layout from "#layouts/default";
import ContentContainer from "#components/ContentContainer";
import { request } from "graphql-request";
async function fetchData() {
const endpoint = "https://localhost:3090/graphql"
const query = `
query getItems($id: ID) {
item(id: $id) {
title
}
}
`;
const variables = {
id: "123123123"
};
const data = await request(endpoint, query, variables);
// console.log(JSON.stringify(data, undefined, 2));
return data;
}
const TestingGraphQL = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
// useEffect with an empty dependency array works the same way as componentDidMount
useEffect(async () => {
try {
// set loading to true before calling API
setLoading(true);
const data = await fetchData();
setData(data);
// switch loading to false after fetch is complete
setLoading(false);
} catch (error) {
// add error handling here
setLoading(false);
console.log(error);
}
}, []);
// return a Spinner when loading is true
if(loading) return (
<span>Loading</span>
);
// data will be null when fetch call fails
if (!data) return (
<span>Data not available</span>
);
// when data is available, title is shown
return (
<Layout>
{data.item.title}
</Layout>
);
};
since fetchData() returns a promise you need to handle it in TestingGraphQL. I recommend onComponentMount do your data call. Setting the data retrieved into the state var, for react to keep track of and re-rendering when your data call is finished.
I added a loading state var. If loading is true, then it shows 'loading' otherwise it shows the data. You can go about changing those to components later to suit your needs.
See the example below, switched from hooks to a class, but you should be able to make it work! :)
class TestingGraphQL extends Component {
constructor() {
super();
this.state = { data: {}, loading: true};
}
//when the component is added to the screen. fetch data
componentDidMount() {
fetchData()
.then(json => { this.setState({ data: json, loading: false }) })
.catch(error => console.error(error));
}
render() {
return (
{this.state.loading ? <div>Loading Spinner here</div> : <div>{this.state.data.item.title}</div>}
);
}
};
I'm creating my first MERN stack application, and trying to implement a simple API that calls my express server from my React front-end components. I have the API working on the back end, and it is sending the data correctly through fetch(), but I'm having trouble resolving the promise from fetch() in my React component, with the call not stopping firing. My code looks as follows (assuming as of right now all API calls return a dummy format like { title: 'foo', ... }:
import React, { useState } from 'react';
import 'core-js/stable';
import 'regenerator-runtime/runtime';
const getApiData = async (route) => {
try {
let apiData = await fetch(route);
let apiDataJson = await apiData.json();
return apiDataJson;
} catch (err) {
throw new Error('Error on fetch', {
error: err
})
}
}
var retrieve_data = async (route, setterCallback) => {
await getApiData(`/api/${route}`).then((data) => {
console.log('Data retrieved from API')
setterCallback(<div>{data.title}</div>)
}).catch(() => {
setterCallback(<div>ERROR</div>)
})
}
const MyComponent = () => {
const [innerDiv, setinnerDiv] = useState(0);
let data = retrieve_data('myEndpoint', setinnerDiv);
return(
<div>
<h1>Data Retrieved in MyComponent:</h1>
{innerDiv}
</div>
);
}
When I compile the above the component successfully renders (i.e. <MyComponent /> looks like:
<div>
<h1>Data Retrieved in MyComponent:</h1>
<div>foo</div>
</div>
However, then then block keeps executing (i.e. the 'Data retrieved from API' logs to the console hundreds of times/second until I close the application. How can I stop this from executing once it has set the component? Thanks!
You need to useEffect to stop the component from re-rendering. Try something like this.
const MyComponent = () => {
const [innerDiv, setinnerDiv] = useState(0);
useEffect(() => {
retrieve_data('myEndpoint', setinnerDiv);
}, []);
return(
<div>
<h1>Data Retrieved in MyComponent:</h1>
{innerDiv}
</div>
);
}
I am builing my first app in React. I have data in XML file using xml2js converting them to json object abd then i am trying to return title every single AD but without success. I think that may be a problem with this part .then(data => this.setState({postsList: [data]})?
import React, {Component} from 'react';
import {parseString} from 'xml2js'
class AdListing extends Component {
state = {
postsList: [],
};
componentDidMount() {
fetch('export.xml')
.then(response => response.text())
.then(responseText => {
parseString(responseText, function (err, data) {
console.log(data) [1]
return data
})
})
.then(data => this.setState({
postsList: [data]
}));
};
renderList = () => this.state.postsList.map((item, id) => <div>>{item.JOB_TITLE}></div>);
render(){
return(
<div>
<p>oleole</p>
{this.renderList()}
</div>
)
}
}
export default AdListing;
[1] Array looks like: https://i.stack.imgur.com/xQUB0.png