How to send data to another page in ReactJS - javascript

Here I have a problem in ReactJS, in the POST fetch section in NewCases.jsx. There will generate Data i.e. app_uid, then I want to send app_uid data from NewCases.jsx to DNNewCases.jsx, but I don't know how.
This is the Full Script:
NewCases.jsx
import React, { Component, Fragment } from 'react';
import './NewCases.css'
import user2 from '../../images/user2.png';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import DNNewCases from '../DynaformCases/DNNewCases';
class NewCases extends Component {
constructor(props) {
super(props)
this.state = {
token: sessionStorage.getItem("access_token"),
username: sessionStorage.getItem("username"),
user_role: '',
allcases: [],
inMemoryCases: [],
showProcess: [],
dataSess: [],
app_uid: '',
dataselanjutnya: '',
search: '',
}
this.getDetailCase = this.getDetailCase.bind(this);
this.searchData = this.searchData.bind(this);
}
componentDidMount() {
if (window.sessionStorage.getItem("access_token") === null) {
this.props.history.push('/');
}
fetch('https://bpm.*************.or.id/api/1.0/************/extrarest/session-id', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
dataSess: responseJson,
});
});
fetch("https://bpm.***********.or.id/api/1.0/***********/extrarest/login-user", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
}
}).then(result => result.json()).then(resultJSON => {
this.getUserRole(resultJSON.uid);
})
fetch('https://bpm.**************.or.id/api/1.0/************/case/start-cases', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson[0]);
this.setState({
allcases: responseJson,
inMemoryCases: responseJson,
});
});
}
getUserRole = (uid) => {
fetch("https://bpm.***********.or.id/api/1.0/************/user/" + uid, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
}
}).then(result => result.json()).then(resultJSON => {
if (resultJSON.usr_role == "PROCESSMAKER_ADMIN") {
this.setState({ user_role: 'Administrator' })
} else if (resultJSON.usr_role == "PROCESSMAKER_OPERATOR") {
this.setState({ user_role: 'Operator' })
} else if (resultJSON.usr_role == "PROCESSMAKER_MANAGER") {
this.setState({ user_role: 'Manager' })
}
})
}
getDetailCase(pro, tas) {
fetch("https://bpm.***************.or.id/api/1.0/************/cases/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
showProcess: responseJson,
});
this.state.app_uid = (this.state.showProcess.app_uid);
});
}
searchData = (event) => {
this.setState({ search: event.target.value })
const searchData = this.state.inMemoryCases.filter(
data => {
let lowerCase = (data.pro_title).toLowerCase()
let searchLowerCase = this.state.search.toLowerCase()
return lowerCase.indexOf(searchLowerCase) > -1;
}
);
this.setState({ allcases: searchData });
}
render() {
return (
<Fragment>
<div className="background-nya">
<div className="header">
<Link style={{ textDecoration: 'none' }} to="/menu">
<p className="headerLabel-fix"> ********** </p>
</Link>
<p className="headerLabelUser"> {this.state.username} </p>
<p className="headerLabelPass"> {this.state.user_role} </p>
<img className="userIcon" src={user2} />
</div>
<p className="titlePage"> PROCESS LIST </p>
<div className="form-search">
<input type="text" value={this.state.search} onChange={this.searchData} placeholder="search"></input>
</div>
<br />
{
this.state.allcases.map((process) => {
{ this.getDetailCase(process.pro_uid, process.tas_uid) }
return (
<Fragment>
<Link
to={{
pathname: "/dynaform",
state: this.state.app_uid
}}
>
<div key={process.pro_uid} className="caseList" onClick={this.alertShow}>
{process.pro_title}
</div>
</Link>
</Fragment>
)
})
}
</div>
</Fragment>
)
}
}
export default NewCases;
DNNewCases.jsx
import React, { Component, Fragment } from 'react';
import user2 from '../../images/user2.png';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Iframe from 'react-iframe'
class DNNewCases extends Component {
constructor(props) {
super(props)
this.state = {
username: sessionStorage.getItem("username"),
token: sessionStorage.getItem("access_token"),
dataSess: [],
}
}
componentDidMount() {
if (window.sessionStorage.getItem("access_token") === null) {
this.props.history.push('/');
}
fetch('https://bpm.**********.or.id/api/1.0/**********/extrarest/session-id', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
dataSess: responseJson,
});
});
}
render() {
return (
<Iframe url= {'https://bpm.************.or.id/***********/en/neoclassic/cases/open?APP_UID=&DEL_INDEX=1&action=EDIT&sid=' + this.state.dataSess}
width="100%"
height="100%"
display="block"
position="fixed" />
)
}
}
export default DNNewCases;
Hopefully I can find a solution here. Thank you very much

I would suggest using "react-redux".
With mapDispatchToProps and some actions, you could save the new data in a reducer, then you could access the data with mapStateToProps.
Links above provide some examples and I personally recommend youtube tutorials from techsith.

you can use props when navigating between components,
Have a look at this, to pass data between router link
if not for a better solution, try using Redux.
youtube tutorial click here

I suggest the usage of withRouter
export default withRouter(props => <NewCases {...props} />);
From ReactTraining Docs:
You can get access to the history object’s properties and the closest
's match via the withRouter higher-order component. withRouter
will pass updated match, location, and history props to the wrapped
component whenever it renders.
Once you get access to your history, make use of this snippet to reroute:
this.props.history.push(`/someRoute`);
Simply call this snippet in your setState callback after your API call & after you've set the correct state to app_uid. As I stated in my comment, it appears you are directly mutating your state. I highly suggest to set the new app_uid inside the setState function
As a side note: I do not see your Route configurations. This answer assumes you've at least set up your client-side-routing on your original code base.

Related

How to get HTML tag from API response in React Js?

I have a response from Api like the following:
data: {
id : 20,
name : "Michael",
content : "Today is <p>my special day in my life</p> thankyou"
}
and in react code as follows:
const dataMain = useselector((state) => state.main.data)
return (
<>
<div>
<div className="name"><h2>{dataMain.name}</h2></div>
<div className="the-content" dangerouslySetInnerHTML={{__html: dataMain.content></div>
</div>
</>
)
Result :
Michael,
Today is <p>my special day in my life</p> thankyou
The html P tag is still there, while I want it to disappear
When setting your content in dangerouslySetInnerHTML try ${dataMain.content} otherwise set the value to state variable using ${} syntax. This has worked for me on other compnents with HTML tags.
Example below:
class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
content: null
}
}
componentDidMount() {
const payload = {};
fetch("/example",{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
})
.then((response) => {
return response.text();
})
.then((text) => {
this.setState({
isLoaded: true,
content: `${text}`
});
});
}
render() {
return (
<React.Fragment>
{!this.state.isLoaded &&
<div className="text-info">
Please wait...
</div>
}
{this.state.isLoaded &&
<div id="terms-content" dangerouslySetInnerHTML={{__html: this.state.content}}/>
}
</React.Fragment>
)
}
}

Uncaught (in promise) SyntaxError: Unexpected end of JSON input when fetch get data

Is there any way to check if the data already fetched or not? Because when I debugged the code it received the below error -
Uncaught (in promise) SyntaxError: Unexpected end of JSON input.
I have already tried to debug and also tried with different api.
Also when I test APIs in postman I am able to receive the response and from that I can conclude that API is working fine.
Can anyone correct me and point me where I am doing wrong as I am new to react.
Below is the code -
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Table } from 'react-bootstrap';
import * as Constants from '../constant'
class ViewUser extends Component {
constructor(props) {
super(props);
this.state = {
myJson: [
{ username: null, createdDate: null, createdBy: null }
],
};
}
componentDidMount() {
fetch(Constants.API_URL + 'api/user', {
method: 'GET',
headers: {
"Authorization": "Bearer 733a7570-c39a-4fff-99e8-bcc38c1aad58",
"Content-Type": "application/json"
}
})
.then(function (response) {
console.log(response)
return response.json();
})
.then((myJson) => {
this.setState({
myJson: myJson
});
console.log(myJson)
});
}
delete = (myJson) => {
console.log(myJson)
const requestOptions = {
method: 'DELETE',
headers: {
"Authorization": "Bearer 733a7570-c39a-4fff-99e8-bcc38c1aad58",
"Content-Type": "application/json"
}
}
fetch(Constants.API_URL + 'api/authority/' + myJson.authority, requestOptions)
.then(response => response.text())
}
edit = (myJson) => {
// Do whatever you want
console.log(myJson)
// history.push("/editAuthority")
this.props.history.push({
pathname: 'authority' + "/" + myJson.authority,
state: { authority: myJson.authority, description: myJson.description }
})
}
render() {
return (
<div className="container-fluid">
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>username</th>
<th>createdDate</th>
<th>createdBy</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{
this.state.myJson.map((item, key) => {
return (
<tr key={key} >
<td>{item.username}</td>
<td>{item.createdDate}</td>
<td>{item.createdBy}</td>
<td><center><button className="btn btn-primary btn-xs" onClick={() => this.edit(item)}>Edit
</button></center></td>
<td><center><button className="btn btn-primary btn-xs" onClick={() => this.delete(item)}>Delete
</button></center></td>
</tr>
)
})}
</tbody>
</Table>
</div>
);
}
}
export default ViewUser;

How to POST data from this.state?

I'm trying to use this.state in a POST call with Axios, and I can't understand why it isn't working. I tried to connect (getting a "bind () is not a function" error) and setState, but nothing seems to work . I can't find any good solution for this problem, follow the code below, thanks for your help in advance!
import ReactDOM from 'react-dom';
import axios from 'axios';
class AccountSettings extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
projects: "Loading...",
};
}
componentDidMount() {
fetch("/../api/****/account/projects")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
projects: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
saveProjects(event) {
axios.post('/../api/****/account/projects/save',{
projects: this.state.projects,
})
.then()
.catch();
event.preventDefault();
}
handleOnChange(event) {
this.setState({
projects: event.target.value
})
}
render() {
return (
<form method="post" onSubmit={this.saveProjects}>
<label htmlFor="projectsInput">My projects</label>
<textarea className="form-control" id="projectsInput" rows="3" aria-describedby="projectsInputHelp"
name="projectsInput" value={this.state.projects}
onChange={(event) => this.handleOnChange(event)} />
<small id="projectsInputHelp" className="form-text text-muted">
Add every project on a new line.<br/><br/>
</small>
<button type="submit" className="btn btn-primary">
Save projects
</button>
</form>
)
}
}
ReactDOM.render(<AccountSettings />, document.getElementById("account-settings"));```
Binding works for me this.saveProjects=this.saveProjects.bind(this); and if somehow binding fails then you can always use arrow functions in class components.
I'm doing this:
let data = Object.keys(this.state.fields).map(key => encodeURIComponent('formName['+key+']') + '=' + encodeURIComponent(this.state.fields[key])).join('&'))
fetch('....', {
method: "POST",
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json, text/javascript, */*',
'X-Requested-With': 'XMLHttpRequest' <--- if needed for php framework isXmlHTTPRequest()
}
})
.then( response => response.json() )
.then( json => {
console.log(json);
})
.catch(error => console.log(error))

React-Native | Problem with setState can't be read

The setState can't be read, the value of print1 stays 0000 it must be changed to array[0].date and the alert shows the value of array[0].date
the problem is that it works before.
PS: there's no error shown
export default class WebServiceUse extends Component {
constructor(props) {
super(props);
this.state = ({
print1: '0000',
})
}
componentDidMount() {
fetch('https://**********', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: '1' })
}).then((response) => response.json()).then((responseJson) => {
let array = responseJson.ed5aaf3d933385698d872d0a0d5d4f36
alert(array[0].date)
this.setState = ({
print1: array[0].date,
})
})
.catch((error) => {
console.error(error)
});
}
render() {
return (
<View style={styles.container}>
<Text>Test:</Text>
<Text>{this.state.print1}</Text>
</View>
);
}
}
When you set the state in the constructor, this.state = is assigning the initial value of the state object so it's not really a function. Further down the lifecycle calling this.setState IS a function that merges existing state with your changes. So change
this.state = ({
print1: '0000',
})
to
this.state = {
print1: '0000'
}
Also you're not assigning state, you're calling the function so don't use =
this.setState = ({
print1: array[0].date,
})
ought to be
this.setState({
print1: array[0].date
})
Try doing this
export default class WebServiceUse extends Component {
constructor(props) {
super(props);
this.state = ({
print1: '0000',
})
}
componentDidMount() {
var that = this;
fetch('https://**********', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: '1' })
}).then((response) => response.json()).then((responseJson) => {
let array = responseJson.ed5aaf3d933385698d872d0a0d5d4f36
alert(array[0].date)
that.setState({
print1: array[0].date,
})
})
.catch((error) => {
console.error(error)
});
}
render() {
return (
<View style={styles.container}>
<Text>Test:</Text>
<Text>{this.state.print1}</Text>
</View>
);
}
}

ReactJS & Redux access state "constructor" from another file

I'm just trying to post a data everything working fine if I put the fetch function in the same file but when I moved it to another file it shows cannot read property, I've tried this.props instead of this.state, how can I connect this file to constructor()
scr/component/layout.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import { fetchUsers, postUsers } from '../actions/usersAction';
class Layout extends Component {
constructor(){
super()
this.state = {
name: '',
age: ''}
}
onUserUpdate(filed, event){
console.log('onUserUpdate: ' + filed + '==' + event.target.value);
if (filed == 'name') {
this.setState({
name: event.target.value
})
return
}
if (filed == 'age') {
this.setState({
age: event.target.value
})
return
}
}
componentDidMount() {
this.props.fetchUsers();
}
render() {
const { act } = this.props;
const fetchUserss = act.users.map(d => <tr key={d.id}><td>{d.name}</td><td>{d.age}</td></tr>);
return (
<div className="App">
<label>
name:
</label>
<input type="text" name="name" onChange={this.onUserUpdate.bind(this, 'name')} placeholder="Enter Name"/>
<label>
age:
</label>
<input type="text" name="age" onChange={this.onUserUpdate.bind(this, 'age')} placeholder="enter username"/>
<button type="simpleQuery" onClick={this.props.postUsers.bind(this)}>Add News</button>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
{fetchUserss}
</tbody>
</table>
</div>
);
}
}
function mapStateToProps(state) {
return {
act: state.users,
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({fetchUsers, postUsers}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(Layout);
src/actions/userAction.js
export const fetchUsers = (data) =>{
return{
type: "USERS",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
}
};
export const postUsers = (event) =>{
let users = {
name: this.state.name,
age: this.state.age
}
return{
type: "USERS_POST",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(users),
})
.then(res => res.json())
}
};
src/reducers/userReducer.js
const initalState = {
fetching: false,
fetched: false,
users: [],
error: null
};
export default function(state=initalState, action) {
let newState = Object.assign({}, state);
switch(action.type){
case "USERS_PENDING":{
return {...state, fetching: true,loading: false,}
}
case "USERS_FULFILLED":{
return {...state, fetching:false, fetched: true, users: action.payload,}
}
case "USERS_REJECTED":{
return {...state, fetching: false, error: action.payload,}
}
case "USERS_POST_PENDING":{
return {...state, fetching: true,}
}
case "USERS_POST_FULFILLED":{
return newState;
}
case "USERS_POST_REJECTED":{
return {...state, fetching: false, error: action.payload,}
}
default:
return state;
}
}
Please let me know if I miss out any information.
If this has already been asked, I would greatly appreciate if you are able to point me in the right direction.
Thank you so much!
You need to pass that data to your postUsers() function.
<button
type="simpleQuery"
onClick={() => this.props.postUsers(this.state.name,this.state.age)}
>Add News</button>
Then in your postUsers() function should take in those parameters:
export const postUsers = (name, age) => ({
type: "USERS_POST",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
age,
}),
})
.then(res => res.json())
});
We cannot access state outside of a component. You can pass the state variables are params to the postUsers function.
<button type="simpleQuery" onClick={this.props.postUsers(this.state.name,this.state.age)}>Add News</button>
And in your postUsers function
export const postUsers = (name,age) =>{
let users = {
name: name,
age: age
}
return{
type: "USERS_POST",
payload: fetch('http://rest.learncode.academy/api/johnbob/friends',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(users),
})
.then(res => res.json())
}
};
I can see that you have tried to bind a scope to an arrow function. You cannot do that. Arrow functions do not have a scope.
Instead, you should write a normal function.
either,
let postUsers = function() {};
or
function postUsers(){}
In other words this inside an arrow function is always inherited from the parent function. So in your case, this is not undefined, but it is not the this you expect.

Categories

Resources