importing a state value from react class component - reactjs

In my App.js I have this state object:
App.js
this.state = {
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
Authorization:
"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianR}
};
I want to export this.state.headers to my globalMethods.js file, which has a data posting function:
globalMethods.js
export function submitUserData() {
fetch("http://dev.test.lt/be/api/user/data", {
method: "POST",
body: JSON.stringify(data),
headers // <-- this exact variable has to be this.state.headers
})
.then(response => response.json())
}
Can't export headers from App.js, since export const headers = this.state.headers cannot access "this" scope.
Exports within App class are, of course, not possible.
Are there any other options?

You can pass the variable when you are calling the submitUserData.js.
callingUrl = () => {
const response = submitUserData(this.state.headers)
}
So your function should be like this...
export function submitUserData(customHeaders) {
fetch("http://dev.test.lt/be/api/user/data", {
method: "POST",
body: JSON.stringify(data),
headers: customHeaders
})
.then(response => response.json())
}

What you need is global state analog.
So my advice would be to create some plain js module named requestHelper.js with property
export const requestHeaders = headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",}
and exporting method setHeader(name, value)
import that method into your app component, and call it on auth request success. Later get your headers from requestHelper.requestHeaders object anywhere in your app

You need some kind external intermediate container to do that. E. g. you can make your component save headers to localStorage or use Redux for that.
Or do it backwards: export your headers from globalMethods.js and use it inside class.

have you tried this:
import React from "react"
const header ={};
class App extends React.Component {
constructor(){
super()
this.state = {
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
Authorization:
"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianR}
};
}
render() {
header = this.state.headers
return <div/>
}
}
export header

Related

I am trying to make a post request in a API from React but i get "net::ERR_ABORTED 415"

here is the code and here is the web api that i am connecting to "https://hub.graphistry.com/api-token-auth/", i have try to use axios but id doesn't help with the cors
import React, { Component } from "react";
export default class App extends Component {
async postData() {
try {
let result = await fetch("https://hub.graphistry.com/api-token-auth/", {
method: "post",
mode: "no-cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: "orlando",
password: "graphistry1234",
}),
});
console.log(result);
} catch (e) {
console.log(e);
}
}
render() {
return (
<div>
<button onClick={() => this.postData()}>
Press me to post some data
</button>
</div>
);
}
}
In this case, you need to use form-data as bellow:
let formData = new FormData();
formData.append("username", "orlando");
formData.append("password", "graphistry1234");
fetch("https://hub.graphistry.com/api-token-auth/", {
method: "POST",
body: formData
})
fetch() does not expect a JavaScript object at body. curl command and fetch() pattern are not the same.

Put call in reactjs

This is my service method , where I need to do the put call to an API by passing an id. Is this the correct way, bcoz I am not able to hit my .put URL
ENDPOINTS = {
SAMPLE: "/sample",
};
This is my service method:
updateApi(): Promise<any> {
const config = {
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
// data
};
const id = sample.id;
return http
.put(`${this.ENDPOINTS.SAMPLE}${id}`, data, config)
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
I believe your issue is the line const {id} = sample.id;
This should instead be: const { id } = sample; or the equivalent const id = sample.id.
In addition, your API endpoint is missing a trailing /, so you should include it in your .put() call.
Example: ${this.ENDPOINTS.SAMPLE}/${id}
Not sure if you have any reason for using http here but if you are flexible then try fetch API available in react.
const requestOptions = {
method: 'PUT',
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
body: data
};
fetch(`${ENDPOINTS.SAMPLE}/${sample.id}`, requestOptions)
.then(response => response.json())
.then(data => this.setState({ // update data here }));
If you are directly making call to API in your component then above code can be placed inside componentDidMount.
Let me know if you face any issue!

Cant Save Post Request Body Data

I am having trouble saving the data from a fetch post request using Node.js and React.js. I am calling the fetch request from a function inside a React component class. I want to query some userid from my database then save it to one of the React component instance variables ie "this.userid" however, whenever I assign the value to one of the empty variables I check it outside of the ".then" statements you can see it was never assigned.
Does anyone know of a run around or the proper way to perform the fetch request? I am creating a simple login post request and want to save the userid once its returned from the API.
class LandingPage extends React.Component {
constructor(props) {
super(props)
this.data = data
}
login(e){
var that = this;
function log(id){
that.userid = id
}
fetch("/login", {
method: "POST",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: JSON.stringify(this.data)
}).then(response => {
return response.json();
})
.then(json =>log(json.userid))
/both show undefined
console.log(that.userid, this.userid)
}
You are checking the data outside of the then scope. It doesn't exist there, so you will have to call setState with the retrieved data inside the .then().
change
.then(json =>log(json.userid))
to
.then(json => {
that.setState({userid: json.userid})
})
then, after the component updated, the state with userid is available
Update: alternatively, you can use async await and build it like this:
import React from 'react';
class MyComponent extends React.Component {
state = {
userId: null
}
useFetch = async e => {
const raw = await fetch("/login", {
method: "POST",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.data)
});
const json = await raw.json();
this.setState({
userId:json
}, () => console.log(this.state))
}
render() {
if (this.state.userId === null)
this.useFetch();
return (
<div>Loading some data</div>
)
}
}
export default MyComponent;
tested and working component.

Stub a closure function using sinon for redux actions

I have an redux action which has an async call to an API.
import { ForbiddenRequest, APIError } from "../errors"
import { fetchActionCreator } from "redux-fetch-helpers"
export const ADD_CART_ITEMS = "ADD_CART_ITEMS"
export default function addCartItems(items, authToken){
return fetchActionCreator({
url: `${API_BASE}/ajax_cart`, //eslint-disable-line no-undef
fetchOptions: {
method: "POST",
headers: new Headers({
"Authorization": `jwt ${authToken}`,
"Accept": "application/json",
"Content-Type": "application/json",
}),
body: JSON.stringify(items),
credentials: "same-origin",
},
actionType: ADD_CART_ITEMS,
responseConfig: {
200: (resp => resp),
403: (payload => new ForbiddenRequest(payload)),
other: (payload => new APIError(payload)),
}
})
}
I am trying to mock the fetchActionCreator method by using sinon stubs.
This is my spec file
import addCartItems from "../../actions/addCartItems"
import sinon from "sinon"
describe("The addCartItems action", () => {
let fetchActionCreator
it("should create an action to add an item into the cart", () => {
const addedCartItem = {
items: [{product_variant: 10, quantity: 1}]
}
const expectedAction = { type: "ADD_CART_ITEMS", meta: {sequence: "BEGIN"}}
fetchActionCreator = sinon.stub()
// fetchActionCreator()
fetchActionCreator.returns(expectedAction)
expect(addCartItems(addedCartItem, "someToken")).to.equal(expectedAction)
})
})
But somehow the function is not getting mocked. Can you suggest me the right way.
You need to stub the actual function from the library that is being called, not just create a stub that has the same name.
Add the following to your imports in your tests:
import * as reduxFetchHelpers from 'redux-fetch-helpers';
Then to the body of your test, replace your current stub code with:
const fetchActionCreator = sinon.stub(reduxFetchHelpers, 'fetchActionCreator');
fetchActionCreator.returns(expectedAction);
I have not tested this code but it looks like it should work.

How to make a rest post call from ReactJS code?

I am new to ReactJS and UI and I wanted to know how to make a simple REST based POST call from ReactJS code.
If there is any example present it would be really helpful.
Straight from the React Native docs:
fetch('https://mywebsite.example/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
(This is posting JSON, but you could also do, for example, multipart-form.)
Also see docs for ReactJS AJAX FAQs if not using React Native.
React doesn't really have an opinion about how you make REST calls. Basically you can choose whatever kind of AJAX library you like for this task.
The easiest way with plain old JavaScript is probably something like this:
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(data);
In modern browsers you can also use fetch.
If you have more components that make REST calls it might make sense to put this kind of logic in a class that can be used across the components. E.g. RESTClient.post(…)
Another recently popular packages is : axios
Install : npm install axios --save
Simple Promise based requests
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
you can install superagent
npm install superagent --save
then for make post call to server
import request from "../../node_modules/superagent/superagent";
request
.post('http://localhost/userLogin')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ username: "username", password: "password" })
.end(function(err, res){
console.log(res.text);
});
As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:
import axios from 'axios';
...
class Login extends Component {
constructor(props, context) {
super(props, context);
this.onLogin = this.onLogin.bind(this);
...
}
async onLogin() {
const { email, password } = this.state;
try {
const response = await axios.post('/login', { email, password });
console.log(response);
} catch (err) {
...
}
}
...
}
I think this way also a normal way. But sorry, I can't describe in English ((
submitHandler = e => {
e.preventDefault()
console.log(this.state)
fetch('http://localhost:5000/questions',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state)
}).then(response => {
console.log(response)
})
.catch(error =>{
console.log(error)
})
}
https://googlechrome.github.io/samples/fetch-api/fetch-post.html
fetch('url/questions',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state)
}).then(response => {
console.log(response)
})
.catch(error =>{
console.log(error)
})
Here is a the list of ajax libraries comparison based on the features and support.
I prefer to use fetch for only client side development or isomorphic-fetch for using in both client side and server side development.
For more information on isomorphic-fetch vs fetch
Here is a util function modified (another post on stack) for get and post both. Make Util.js file.
let cachedData = null;
let cachedPostData = null;
const postServiceData = (url, params) => {
console.log('cache status' + cachedPostData );
if (cachedPostData === null) {
console.log('post-data: requesting data');
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then(response => {
cachedPostData = response.json();
return cachedPostData;
});
} else {
console.log('post-data: returning cachedPostData data');
return Promise.resolve(cachedPostData);
}
}
const getServiceData = (url) => {
console.log('cache status' + cachedData );
if (cachedData === null) {
console.log('get-data: requesting data');
return fetch(url, {})
.then(response => {
cachedData = response.json();
return cachedData;
});
} else {
console.log('get-data: returning cached data');
return Promise.resolve(cachedData);
}
};
export { getServiceData, postServiceData };
Usage like below in another component
import { getServiceData, postServiceData } from './../Utils/Util';
constructor(props) {
super(props)
this.state = {
datastore : []
}
}
componentDidMount = () => {
let posturl = 'yoururl';
let getdataString = { name: "xys", date:"today"};
postServiceData(posturl, getdataString)
.then(items => {
this.setState({ datastore: items })
console.log(items);
});
}
Here is the simple method to define and call post APIs in reactjs. Install axios using command npm install axios and call post req method wherever you want, it will return array that contains 100 elements.
// Define post_req() Method in authAction.js
import axios from 'axios';
const post_req = (data) => {
return new Promise((resolve, reject) => {
const url = 'https://jsonplaceholder.typicode.com/posts'
const header = {
"Access-Control-Allow-Origin": "*",
"Content-Type: application/json"
}
axios({
method: 'post',
url: url,
data: data,
headers: header
});
.then((res)=>{resolve(res);})
.catch((err)=>{reject(err);})
})
}
// Calling post_req() Method in react component
import React, { Component } from 'react';
import { post_req } from 'path of file authAction.js'
class MyReactComponent extends Component {
constructor(props) {
super(props);
this.state = {
myList:[]
};
}
componentDidMount() {
let data = {
.......
}
this.props.post_req(data)
.then((resp)=>{this.setState({myList:resp.data})})
.catch((err)=>{console.log('here is my err',err)})
}
render() {
return (
<div>
....
</div)
}
}
export default MyReactComponent;
import React ,{useState}from 'react';
import Axios from 'axios';
export default function Formlp()
{
const url ="";
const [state, setstate] = useState({
name:"",
iduser:""
})
function handel(e){
const newdata={...state}
newdata[e.target.id]=e.target.value
setstate(newdata);
}
function submit(e)
{
e.preventDefault();
// Axios.post(url,{name:state.name,iduser:state.iduser}).then( res=>{console.log(res)});
console.log(state)
}
return (
<div onSubmit={ (e)=> submit(e)}>
<input onChange={ (e)=>handel(e) } id="name" value={state.name} placeholder="name" type="text" >
<input onChange={ (e)=>handel(e) } id="iduser" value={state.iduser} placeholder="iduser" type="text" >
<button>submit</button>
</form>
</div>
);
}
Here is a quick example for v18+ while handling form data and creating a POST request with the data.
async function handleOrderSubmit(event){
event.preventDefault()
try{
const formData= {name: event.target.name.value, email: event.target.email.value, message: event.target.name.message}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
};
const response = await fetch('https://www.example.com/form', requestOptions);
const data = await response.json();
navigate("/form-response", { state: {data: data, status: true} })
}
catch(error){
navigate("/form-response", { state: {status: false} })
}
}
Note 1: Using status on '/form-response' page, you can customise what to show user. For true, you can show a different section and for false a different one.
Note 2: If the status is successful, you can access data on the next page also and customise it according to user information.
Note 3: event.preventDefault() is important to avoid page reloading.
Here is an example: https://jsfiddle.net/69z2wepo/9888/
$.ajax({
type: 'POST',
url: '/some/url',
data: data
})
.done(function(result) {
this.clearForm();
this.setState({result:result});
}.bind(this)
.fail(function(jqXhr) {
console.log('failed to register');
});
It used jquery.ajax method but you can easily replace it with AJAX based libs like axios, superagent or fetch.

Resources