***This component makes a REST API call and parses promise value and renders the data in the form of a table.
load(function) makes the API call and takes orderType as input. OrderType is passed as a query parameter from the navigation component which is not included here.
class SampleController extends React.Component {
constructor(props){
super(props);
let orderType = this.props.location.query.orderType;
this.load = this.load.bind(this);
this.load(orderType);
this.state = {orderType: orderType, data: null}
}
load(orderType) {
let self = this;
console.log("order type is" + orderType);
let baseURL = base_urls.orderMetricsBaseURL;
console.log("base URL is", baseURL);
let url = baseURL + "/getData";
let response_data = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
order_type: orderType
})
})
.then((response) => response.json())
.then((responseJson) => {
let order_data = responseJson;
console.log("responseeeeee is: ", order_data);
self.setState({data: order_data});
self.forceUpdate();
})
.catch((error) => {
console.error(error);
});
}
render() {
var content = <DataTable dataList = {this.state.data} />;
return (
content
);
}
}
export { SampleController as default };
remove this line this.load(orderType); from constructor and put it inside componentDidMount:
constructor(){
//....
}
componentDidMount() {
const orderType = this.props.location.query.orderType;
this.load(orderType);
}
You need to do setState to trigger a rerun/rerender on your component.
From the documentation:
setState() does not update the state immediately, so there's a chance you are losing that update because of the forceUpdate(), which shouldn't be needed as setState() will trigger a re-render by itself. Try removing the forceUpdate() call.
Update:
In case you want to call your load() method each time your orderType you'd need to subscribe to the componentWillReceiveProps method.
Example:
class SampleController extends React.Component {
constructor(props){
super(props);
let orderType = this.props.location.query.orderType;
this.load = this.load.bind(this);
this.load(orderType);
this.state = {orderType: orderType, data: null}
}
componentWillReceiveProps(nextProps) {
const orderType = nextProps.location.query.orderType;
const prevOrderType = this.props.location.query.orderType;
if (prevOrderType !== orderType) {
this.load(orderType);
}
}
load(orderType) {
let self = this;
console.log("order type is" + orderType);
let baseURL = base_urls.orderMetricsBaseURL;
console.log("base URL is", baseURL);
let url = baseURL + "/getData";
let response_data = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
order_type: orderType
})
})
.then((response) => response.json())
.then((responseJson) => {
let order_data = responseJson;
console.log("responseeeeee is: ", order_data);
self.setState({data: order_data});
})
.catch((error) => {
console.error(error);
});
}
render() {
var content = <DataTable dataList = {this.state.data} />;
return (
content
);
}
}
export { SampleController as default };
Related
I need to fetch the variable which is inside a function in class component. This is my function I want to fetch the "newArray" variable in class component.
handleChanges(event) {
this.setState({value: event.target.value});
console.log("value",event.target.value);
let values=['OurStory','HowItWorks','Blog','Login','BeaParopakari'];
console.log("values",values);
let url =
"http://localhost:49590/api/Authenticate/Translate?values=xxxxxxxxxxxxxxx";
let user = JSON.parse(localStorage.getItem("user"));
const accessToken = user;
console.log(accessToken);
fetch(url, {
method: "GET",
headers: {
"Content-type": "application/json",
Accept: "application/json",
Authorization: "Bearer " + accessToken,
"Access-Control-Allow-Headers": "Access-Control-Request-Headers "
}
})
.then((response) => response.json())
.then((data) => {
this.setState({
Details: data
});
console.log("Filter", data);
const longArray = data;
const size = 1;
const newArray = new Array(Math.ceil(longArray.length / size)).fill("")
.map(function() { return this.splice(0, size) }, longArray.slice());
console.log(this.state.newArray);
const trans = "Vijayaasri";
});
I tried it in state but it didn't work.
{this.state.newArray.map(s=>s.result)}
I use map function to fetch.
enter image description here
This newArray value I need to print in page. Please share your knowledge. Thank You in Advance.
I'm using ReactJs with Material-UI to display a table of Car components but never update after Creating, Editing or Deleting a row.
Next is the structure:
class MainCar extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: []
};
this.apiUrl = "http://localhost:8080/api/v1/cars";
this.onCreate = this.onCreate.bind(this);
this.onUpdate = this.onUpdate.bind(this);
this.onDelete = this.onDelete.bind(this);
this.loadFromServer = this.loadFromServer.bind(this);
}
loadFromServer() {
fetch(this.apiUrl)
.then(response => response.json())
.then(json => {
this.setState({
cars: json.cars
});
});
}
onCreate(newCar) {
try {
const result =
fetch(this.apiUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newCar)
});
} catch(e) {
console.error(e);
}
this.loadFromServer();
}
onUpdate(car, updatedCar) {
try {
const result =
fetch(car._links.self.href, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedCar)
});
} catch(e) {
console.error(e);
}
this.loadFromServer();
}
onDelete(car) {
try {
const result =
fetch(car._links.self.href, {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(car)
});
} catch(e) {
console.error(e);
}
this.loadFromServer();
}
render() {
return (
<CarsTable cars={this.state.cars}
onCreate={this.onCreate}
onUpdate={this.onUpdate}
onDelete={this.onDelete} />
);
}
}
class CarsTable extends React.Component {
constructor(props) {
super(props);
}
render() {
const cars = this.props.cars.map(car =>
<Car key={car._links.self.href}
car={car}
onUpdate={this.props.onUpdate}
onDelete={this.props.onDelete} />
);
return (
<Table>
<TableBody>
{cars}
</TableBody>
</Table>
);
}
}
class Car extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<TableRow>
<TableCell>{car.code}</TableCell>
<TableCell>{car.color}</TableCell>
</TableRow>
);
}
}
As you seen, MainCar has cars array on its state, but CarTable and Car have only properties.
When I log on render functions I see data has changed, however the view is not updated.
View only updates
When I press F5 to update page.
Or when I create, update or delete a new Row I see the previous change but not the last one.
I read that React re-render a component when state has changed. Should I set state for CarTable and Car components copying from props? How can I solve this problem?
Thanks in advance.
What is probably happening is that your GET request is returning before your POST/PUT/DELETE is complete. One way to resolve this is to make sure the GET is only fired after the other action has completed by putting it in a then block.
e.g.
onDelete(car) {
try {
const result =
fetch(car._links.self.href, {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(car)
}).then(a => this.loadFromServer());
} catch(e) {
console.error(e);
}
}
You need to await asynchronous things in JavaScript. Otherwise, you're going to be doing your POST and GET in parallel instead of sequentially. You can use an async function to make this easier.
async onCreate(newCar) {
try {
await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newCar)
});
} catch(e) {
console.error(e);
}
return this.loadFromServer();
}
Your code looks like it should work (I know that's not the most helpful thing to hear when it clearly deosn't), but here's a few things you could try. Try doing bind(this) on your functions in the constructor, and also try calling this.loadFromServer(), not loadFromServer(). Also, I'm guessing you just left this out of your post but you're missing onDelete
See below (look at constructor and onCreate method):
class MainCar extends React.Component {
constructor(props) {
super(props);
this.loadFromServer = this.loadFromServer.bind(this);
this.onCreate = this.onCreate.bind(this);
this.onUpdate = this.onUpdate.bind(this);
this.state = {
cars: []
};
}
loadFromServer() {
fetch(this.apiUrl)
.then(response => response.json())
.then(json => {
this.setState({
cars: json.cars
});
});
}
onCreate() {
// more code to create...
this.loadFromServer(); // to update cars state
}
onUpdate() {
// more code to put...
this.loadFromServer(); // to update cars state
}
render() {
return (
<CarsTable cars={this.state.cars}
onCreate={this.onCreate}
onUpdate={this.onUpdate}
onDelete={this.onDelete} />
);
}
}
I have a state which is an empty array:
constructor(props) {
super(props);
this.state = {
test_steps: [],
};
}
I need to fill up that state with the following data that get when I do a GET request:
See image
UPDATED:
export function copyTestScenarioLog(tSL) {
console.log("\nCalled copyTestScenarioLog");
let url = config.base_url + `/test_scenario_logs`;
return fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getUserToken() },
body: JSON.stringify({
_id: tSL._id['$oid']
})
})
.then(res => res.json())
.then(data => {
getTestStepLogs(data)
return data;
})
.catch(err => console.log(err));
}
export function getTestStepLogs(data) {
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
})
.then(res => res.json())
.then(data => {
console.log(data)
return data
})
.catch(err => console.log(err));
}
How do I update my state after doing a GET fetch?
This is full react component code, you see how I call your funciton in componentDidMount, and in here I pass 'this' as an argument to copyTestScenarioLog.
import React, { Component } from 'react';
import copyTestScenarioLog from './copyTestScenarioLog';
class Component1 extends Component {
constructor(props) {
super(props);
this.state = {
test_steps: []
};
}
componentDidMount() {
var reactComponent = this;
copyTestScenarioLog('i dont konw that is tsl', reactComponent);
}
render() {
return (
<div></div>
);
}
}
export default Component1;
In 'copyTestScenarioLog', I get that ( refers to react component), and use setState function in react.
export function copyTestScenarioLog(tSL, reactComponent) {
console.log("\nCalled copyTestScenarioLog");
let url = config.base_url + `/test_scenario_logs`;
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + getUserToken() },
body: JSON.stringify({
_id: tSL._id['$oid']
})
})
.then(res => res.json())
.then(data => {
getTestStepLogs(data)
reactComponent.setState({
test_steps: data
});
return data;
})
.catch(err => console.log(err));
}
But basically I don't use this approach, I just wanted to show that how its done, I usually use await/async or function generators, because they are better approaches. Search about them and learn to use them.
you can pass onSuccess function into your getTestStepLogs and update your state.
export function getTestStepLogs(data , onSuccess) {
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
}).then(resp => {
if (onSuccess)
onSuccess(resp);
}).catch(err => console.log(err));
}
and when you call getStepLogs pass onSuccess as props:
this.props.getTestStepLogs(data , (resp)=>{
this.setState({test_steps:resp});
})
if you are using the get call at multiple place, you can be little generic and try this approach.
//return here does not do anything right now
export function getTestStepLogs(data) {
return new Promise(function(resolve, reject){
const id = data.test_step_logs[0].$oid;
let url = config.base_url + `/test_step_logs/${id}`;
return fetch(url, {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + getUserToken() }
})
.then(res => res.json())
.then(data => {
console.log(data)
resolve(data);
})
.catch(err => {console.log(err);
reject(err);
});
})
}
async componentDidMount() {
let data = await copyTestScenarioLog();
//now set it to state
}
For an async call, there are three states. Call initiation, call success and call failure. Say "isLoading" represents the status of the call being running in the background.
Initially =>
{
isLoading : false,
data : '',
err : ''
}
Call initiated =>
{
isLoading : true,
data : '',
err: ''
}
Call success =>
{
isLoading : false,
data : response.data
err: ''
}
Call failed =>
{
isLoading :false,
data : '',
err: err
}
Usually, the GET calls of a component are made in componentDidMount. It is also the suggested way as per the react documentation.
componentDidMount(){
//Call Initiation
this.setState({
isLoading : true,
data : '',
err: ''
});
makeApiCall(api).
then((response) => {
this.setState({
isLoading : false,
data : response.data
err: ''
});
},
(err) => {
this.setState({
isLoading :false,
data : '',
err: err
})
})
.catch((err) => {
this.setState({
isLoading :false,
data : '',
err: err
})
})
}
I'm able to loop through JSON data to create an array filled with numbers, but when I go to create the list items it doesn't work. The component just renders an empty list.
When I console.log(ticketNumbers) right before the map function, it shows as a collapsed Array [] until I expand it (it then shows all the values)
function apiCall() {
var ticketNumbers = [];
var memId = 'xxx';
var myInit = {
method: 'GET',
mode: 'cors',
headers: {
'authorization': "xxx",
'Access-Control-Allow-Origin':'*',
'content-type': "application/json",
'cache-control': "no-cache"
},
params: {
'orderBy': 'status/name asc',
'pageSize': 300,
'conditions': "resources contains '" + memId + "' AND status/id not in (17,165,36,163,164,42,73,46,78,148,34,132,45,159,60,168,106,51,72,95)"
}
};
axios.get('Url', myInit)
.then((response) => {
console.log(response.data)
for (var ticket in response.data) {
ticketNumbers.push(response.data[ticket].id)
};
})
return ticketNumbers
}
class TicketContainer extends Component {
constructor(props) {
super(props)
this.state = {
data: [],
loading: true,
};
}
componentWillMount() {
this.setState({
data: {
numbers: apiCall()
},
loading: false
})
};
render() {
return(
<div>
{this.state.loading ? 'Loading' : <Tickets data={this.state.data} />}
</div>
)
}
}
class Tickets extends Component {
render() {
const stuff = this.props;
var ticketList = stuff.data.numbers;
console.log(ticketList);
return(
<div>
<ul>Ticket Number
{ticketList.map((ticket, index) => {
return <li key={index}>sweet</li>;
})}
</ul>
</div>
);
}
}
You should correctly use Promise to solve this. First, let's change apiCall so that it will return a Promise:
function apiCall() {
var ticketNumbers = [];
var memId = 'xxx';
var myInit = {
method: 'GET',
mode: 'cors',
headers: {
'authorization': "xxx",
'Access-Control-Allow-Origin':'*',
'content-type': "application/json",
'cache-control': "no-cache"
},
params: {
'orderBy': 'status/name asc',
'pageSize': 300,
'conditions': "resources contains '" + memId + "' AND status/id not in (17,165,36,163,164,42,73,46,78,148,34,132,45,159,60,168,106,51,72,95)"
}
};
return axios.get('Url', myInit)
.then((response) => {
console.log(response.data)
for (var ticket in response.data) {
ticketNumbers.push(response.data[ticket].id)
}
return ticketNumbers;
});
}
You know have a Promise based api that can be used like this:
apiCall().then(ticketNumbers => console.log(ticketNumbers);
We just need to modify componentWillMount know:
componentWillMount() {
apiCall().then(numbers => this.setState({ loading: false, data: numbers });
}
The apiCall function calls an API which is asynchronous process and returning ticketNumbers from function request won't return the result as the return statement will be executed before the API response is ready and ticketNumbers array is populated.
The easiest way for you to do this is to define this function in the React class and directly setState in the callback of axios request
class TicketContainer extends Component {
constructor(props) {
super(props)
this.state = {
data: [],
loading: true,
};
}
componentWillMount() {
this.apiCall()
};
apiCall =() => {
var memId = 'xxx';
var myInit = {
method: 'GET',
mode: 'cors',
headers: {
'authorization': "xxx",
'Access-Control-Allow-Origin':'*',
'content-type': "application/json",
'cache-control': "no-cache"
},
params: {
'orderBy': 'status/name asc',
'pageSize': 300,
'conditions': "resources contains '" + memId + "' AND status/id not in (17,165,36,163,164,42,73,46,78,148,34,132,45,159,60,168,106,51,72,95)"
}
};
axios.get('Url', myInit)
.then((response) => {
var ticketNumbers = [];
for (var ticket in response.data) {
ticketNumbers.push(response.data[ticket].id)
};
this.setState({data: ticketNumbers, loading: false})
})
}
render() {
return(
<div>
{this.state.loading ? 'Loading' : <Tickets data={this.state.data} />}
</div>
)
}
}
class Tickets extends Component {
render() {
const stuff = this.props;
var ticketList = stuff.data.numbers;
console.log(ticketList);
return(
<div>
<ul>Ticket Number
{ticketList.map((ticket, index) => {
return <li key={index}>sweet</li>;
})}
</ul>
</div>
);
}
}
In case you are wondering why the console.log() statment logs the array, check this answer Value below was evaluated just now in JavaScript object
What i'm trying to do is populate my dropdown list with names that i requested from my API.
Here's my component :
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
my_data: null,
IND: null,
};
};
componentDidMount(){
const query = new URLSearchParams(location.search)
const access_token = query.get('access_token')
const namesId = query.get('namesId')
fetch('http://localhost:8080/api'
+ namesId, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*',
'Authorization': "Bearer " + access_token
}
}).then(response=>{
return response.json();
}).then(data=>{
let my_data = [];
my_data = data;
let individus = hello.individus;
let IND = [];
IND.push({ label: individus[0].lastName, value: individus[0].firstName});
IND.push({ label: individus[1].lastName, value: individus[1].firstName});
IND.push({ label: individus[2].lastName, value: individus[2].firstName});
this.setState({
my_data: hello,
IND: IND
});
}).catch(function(error) {
console.log(error)
});
}
render() {
const { IND } = this.state;
return (
<div>
<Select
multi={true}
joinValues={false}
options={IND}
placeholder="Select"
simpleValue={false}
/>
</div>
);
}
Weirdly all i can see on my dropdown is the first element of this.state.IND ( the 3 objects are in IND, i checked on my console ), i don't understand what i'm doing wrong
Eureka !
Using the "Async options with Promises" of react-select solved my problem