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.
Related
I am getting the data from api. I am displaying Feature ID, DisplayOrder textbox in the rows. User can change the Display Order value in the multiple rows. How to update the information using Post API? I am passing one value FeatureID and DisplayOrder in form submit. Please help to pass all the values that are changed(FeatureID, DisplayOrder) in form submit. If suppose FeatureID 11 and FeatureID 13 Display order changes, then form submit needs to pass these information only.
{"FeatureID":"11","DescriptionText":"Travel","FeatureText":Feature2,"DisplayOrder":"1","Date":"08/30/2011","FeatureName":"Research"},
{"FeatureID":"12","DescriptionText":"Sport","FeatureText":Feature3,"DisplayOrder":"2","Date":"08/30/2011","FeatureName":"Research"},
{"FeatureID":"13","DescriptionText":"Art","FeatureText":Feature4,"DisplayOrder":"3","Date":"08/30/2011","FeatureName":"Research"}]
import React from "react";
export class EditFeatures extends React.Component {
constructor(props) {
super(props);
this.state = {
FeatureID: "",
DisplayOrder: "",
DescriptionText: "",
FeatureText: "",
Feature: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.DisplayFeatures();
}
DisplayFeatures() {
fetch(REQUEST_URL, { "Content-Type": "application/xml; charset=utf-8" })
.then((response) => response.json())
.then((data) => {
this.setState({
Feature: data,
loading: false,
});
});
}
handleSubmit(event) {
event.preventDefault();
const FeatureID = this.state.FeatureID;
const DisplayOrder = this.state.DisplayOrder;
const data = {
FeatureID,
DisplayOrder,
};
fetch(REQUEST_URL, {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
})
.then((response) => response.json())
.catch((error) => console.error("Error:", error))
.then((response) => console.log("Success", data));
window.location.href = "/";
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<table>
<tbody>
{this.state.Feature.map((item, index) => {
return [
<tr key={item.FeatureID}>
<td>
<input
type="text"
id={item.FeatureID}
name="DisplayOrder"
value={item.DisplayOrder}
onChange={(ev) => {
const newFeature = this.state.Feature.map((f) => {
if (f.FeatureID == ev.target.id) {
f.DisplayOrder = ev.target.value;
}
return f;
});
this.setState({ Feature: newFeature });
}}
/>
</td>
<td>{item.DescriptionText}</td>
<td>{item.FeatureTex}</td>
</tr>,
];
})}
</tbody>
</table>
<button type="submit" name="submit">
Update
</button>
</form>
</div>
);
}
}
export default Edit_Features;
The answer is simple, just sort Feature array on DisplayOrder in handleSubmit like this:
import React from "react";
export class EditFeatures extends React.Component {
constructor(props) {
super(props);
this.state = {
FeatureID: "",
DisplayOrder: "",
DescriptionText: "",
FeatureText: "",
Feature: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.DisplayFeatures();
}
DisplayFeatures() {
fetch(REQUEST_URL, { "Content-Type": "application/xml; charset=utf-8" })
.then((response) => response.json()) // you passed Content-Type: "application/xml" as request header but here you use response.json, remove Content-Type header if server API returns json
.then((data) => {
this.setState({
Feature: data.map((feature) => ({ ...feature, changed: false })),
loading: false,
});
});
}
handleSubmit(event) {
event.preventDefault();
const FeatureID = this.state.FeatureID;
const DisplayOrder = this.state.DisplayOrder;
const Feature = this.state.Feature;
const data = {
FeatureID,
DisplayOrder,
Feature, // this is how you pass an array to server, how will the server deserialize this depends on the framework used there
};
const self = this;
fetch(REQUEST_URL, {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
})
.then((response) => response.json())
.catch((error) => console.error("Error:", error))
.then((response) => {
/**
* sort manipulates the array so we clone the Feature array before sorting it
* we pass comparator function to sort so that we sort on DisplayOrder
*/
const newFeature = [...this.state.Feature];
newFeature.sort((f1, f2) => f2.DisplayOrder - f1.DisplayOrder);
self.setState({ Feature: newFeature });
});
window.location.href = "/"; // ok why does this exist?!!
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<table>
<tbody>
{this.state.Feature.map((item) => {
return [
<tr key={item.FeatureID}>
<td>
<input
type="text"
id={item.FeatureID}
name="DisplayOrder"
value={item.DisplayOrder}
onChange={(ev) => {
// this is the proper way to update an element inside an array
const newFeature = [...this.state.Feature];
// I prefer === over == to avoid errors
const featureIndex = newFeature.findIndex(
(f) => f.FeatureID === ev.target.id
);
newFeature[featureIndex].DisplayOrder =
ev.target.value;
this.setState({ Feature: newFeature });
}}
/>
</td>
<td>{item.DescriptionText}</td>
<td>{item.FeatureTex}</td>
</tr>,
];
})}
</tbody>
</table>
<button type="submit" name="submit">
Update
</button>
</form>
</div>
);
}
}
export default EditFeatures;
this way when you click button submit, if the POST request to the server succeeds, the table will be updated according to DisplayOrder.
Note
If the request to the server fails for any reason the table won't be updated, if you don't care about the response of the server just sort the Feature array outside the .then before issuing the request.
there are similiar questions in stackoverflow but I I did not find what I was looking for.
I have a donorDonationForm which is a class componenet that connected to the redux state. The porpuse of that componenet is to collect inormation about a person that want to donate electronics items. At this point, I want to save those items in an array (maybe with an object in the future).
my redux state save the donor info and the reducer looks like this:
import {CHANGE_INPUT_FIELD} from '../utils/constants';
const initialStateInputs = {
// update the state
donorFields: {
name: '',
phone: '',
area: '',
yeshuv: '',
address: ''
// dateOfOffer: ''
},
donationFields: {
// donorID: '',
// vulonteerID: '',
type: [],
quantity: 1,
status: 'NOT_HANDLED',
comments: ''
// lastDateHandled: ''
}
// }, items: [ //need to add quantity
// {id: 1, name: "LAPTOP", isChecked: false, label: 'מחשב'},
// {id: 2, name: "HEADPHONES", isChecked: false, label: 'אוזניות'},
// {id: 3, name: "OTHER", isChecked: false, label: 'אחר'},
// ]
}
export const donorDonationInputsReducer = ( state = initialStateInputs, action={} ) => {
switch(action.type) {
case CHANGE_INPUT_FIELD:
return Object.assign( {}, state,
{
donorFields : {...state.donorFields,...action.payload},
donationFields: {...state.donationFields,...action.payload},
// items : {...state.items,...action.payload},
// isChecked: action.payload
})
default:
return state;
}
}
As you can see the items is commented by now, and I am managing the state of the item in a local state, and that how the comp looks like:
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { setInputField } from '../actions/formAction';
import CheckBox from '../components/CheckBox/CheckBox';
import FormInput from '../components/FormInput/FormInput';
import {selectAreasOptions_2} from '../utils/constants';
import "./form.css";
const mapStateToProps = (state) => {
return {
donorFields: state.donorDonationInputsReducer.donorFields,
donationFields: state.donorDonationInputsReducer.donationFields
}
}
const mapDispatchToProps = dispatch => {
return {
onInputChange: event => {
const {name, value} = event.target;
dispatch(setInputField( { [name]:value} ) )
}
}
}
class donorDonationForm extends Component {
constructor() {
super();
this.state = {
items: [
{id: 1, name: "LAPTOP", isChecked: false, label: 'מחשב'},
{id: 2, name: "HEADPHONES", isChecked: false, label: 'אוזניות'},
{id: 3, name: "OTHER", isChecked: false, label: 'אחר'},
]
,
type: []
}
}
handleCheckChieldElement = (event) => {
let {items, type} = this.state;
let arr = [];
items.forEach(item => {
if (item.name === event.target.value) {
item.isChecked = event.target.checked;
// console.log(`item.name :${item.name }`);
// console.log(`event.target.value :${event.target.value}`);
// console.log(`event.target.checked :${event.target.checked}`);
}
})
items.map(item => item.isChecked ? arr.push(item.name) : null)
this.setState({items: [...items], type: [...arr]});
}
onButtonSubmit = (event) => {
console.log(this.props.donorFields);
event.preventDefault();
fetch('http://localhost:8000/api/donor', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
...this.props.donorFields
})
})
.then(response => response.json())
.then(resp => console.log(resp))
.catch( err => console.log(err) )
}
// componentDidUpdate(prevProps, prevState) {
// const {items, type} = this.state;
// // const type = [];
// if (prevState.items !== items) {
// console.log('items state has changed');
// items.map (item => item.isChecked ?
// this.setState({type: [...type,item.name]}) : null)
// // if (item.isChecked) { type.push(item.name) } ;
// console.log(type);
// }
// }
render() {
console.log(this.state.items);
console.log(this.state.type);
const { onInputChange } = this.props;
return (
<div>
<h1 className="pt4"> פרטי תורם</h1>
<form className=" black-80 pt2" >
<section className=" grid-container">
<FormInput
id="name"
name="name"
type="text"
onInputChange={onInputChange}
label="שם "
required
/>
<FormInput
id="phone"
name="phone"
type="tel"
onInputChange={onInputChange}
label="מספר טלפון "
required
/>
<FormInput
id="address"
name="address"
type="text"
onInputChange={onInputChange}
label="כתובת "
required
/>
<FormInput
id="yeshuv"
name="yeshuv"
type="text"
onInputChange={onInputChange}
label="עיר "
required
/>
<FormInput
id="comments"
name="comments"
onInputChange={onInputChange}
label="הערות "
required
/>
<FormInput
id="area"
name="area"
onInputChange={onInputChange}
label="איזור "
select={selectAreasOptions_2}
/>
{/* type */}
<div className="measure-narrow">
<label htmlFor="type" className="f5 b db mb2">מעוניין לתרום
<span className="normal black-60"> *</span>
</label>
{
this.state.items.map( (item, i) => {
return (
<CheckBox
key={i}
onChange={this.handleCheckChieldElement}
checked={ item.isChecked }
value= {item.name}
label = {item.label}
/>
);
})
}
</div>
</section>
<input type="submit" value="שלח"
className="b bg-light-blue pa2 hover pointer"
onClick={this.onButtonSubmit}
/>
</form>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(donorDonationForm);
My main goal is that the type array - the final donation, will update the redux state before submitting this form. I tried with componentDidUpdate but didn't make it. What is the best way for tracking the checked items, updating the array and then update the type array which is the final donation in the redux state? should I do that in the onButtonSubmit method - before sending the data to the server (and thats way saving the looping over the items array for searching the checked elements) ?
Better approach would be do inside onButtonSubmit
Let me briefly explain the tasks:
inputChangeHandler to update this.state.items
Go with the final this.state.items value Array of items inside onButtonSubmit
After getting API response update the application level Redux state with Array of items.
Note: Dispatch the action. Reducer will update the Redux state. Following code will do this:
// Action
export const setItems = (data) => (dispatch) => {
dispatch({type: 'SET_ITEMS', payload: data})
}
// mapDispatchToProps
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
setItems,
...others
},
dispatch
)
// onSubmitButton
onButtonSubmit = (event) => {
console.log(this.props.donorFields);
event.preventDefault();
fetch('http://localhost:8000/api/donor', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
...this.props.donorFields
})
})
.then(response => this.props.setItems(response.json())) // will update the state.
.then(resp => console.log(resp))
.catch( err => console.log(err) )
}
// Reducer
export const donorDonationInputsReducer = ( state = initialStateInputs, action={} ) => {
switch(action.type) {
case CHANGE_INPUT_FIELD:
return Object.assign( {}, state,
{
donorFields : {...state.donorFields,...action.payload},
donationFields: {...state.donationFields,...action.payload},
// items : {...state.items,...action.payload},
// isChecked: action.payload
})
case SET_ITEMS:
return {
...state,
items: action.payload
}
default:
return state;
}
}
That's it.
Happy Coding :)
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))
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.
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>
);
}
}