React JS error "Cannot read property '0' of undefined" - reactjs

I'm attempting to populate a drop-down box with data consumed from an API; The data in this drop-down box is reflected according to data populated from another drop-down box.
This is my code and where the error occurs:
fetchSimulation(building) {
const bearerToken = this.getToken();
fetch(`http://www.myAPI.com/${param.data}`, {method: 'GET',headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${bearerToken}`
},}).then(results => results.json()).then(simulation => {
this.setState({ segments: simulation.segments, selected: simulation.segments[0].segmentName })
this.props.onSelect(simulation.segments[0])
});
}
Error line:
this.setState({ segments: simulation.segments, selected: simulation.segments[0].segmentName })
this.props.onSelect(simulation.segments[0])
I have two questions:
Question 1: Could there be a syntax issue in the approach am using to pass parameters via the URL in my Fetch?
Question 2: The server my API is hosted on, I also notice that it constantly crashes / go down for about 25-40 minutes and then it's back up. I notice this occurs 3-4 minutes after running my APP. I'm very new to React JS, but could my code be cause of the server going down (is it possible, for example memory leak)?

Related

Chrome and Edge hang on React page load for only some users, should I change my useEffect strategy?

My ReactJS project displays a simple page consisting of a header section with project title, version and a few nav links, then a table of about 200 results as the main content of the page.
The initial page loads for everyone and the components appear as expected, but on page load (I believe this is when the useEffect hook kicks in) some users report the page becoming un-responsive and no matter how long it is left, it never finishes. This has been reported in both Chrome and Edge by 5 different users across a site of 200+ users, the majority have no issues despite running the exact same hardware and connection.
On page load, I expect the title, version and table contents (plus a few other variables) to be populated and automatically updated since these are in state, and for most users, this works as expected.
Below is my useEffect()
useEffect(() => {
// Update all initial values
fetchLastUpdated();
fetchVersion();
fetchUsername();
fetchUpcomingFilterOptions();
fetchLongCustomerNames();
fetchConfigs();
fetchUpcomingResults() // This will be displayed as rows
const job = document.getElementById("job")
if ( !!job ) {
job.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
submitForm()
}
});
}
// Find environment for API links: testing/pre-release, testing/QA, flx
const url = window.location.href
if ( url.includes('localhost') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/pre-release') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/QA') ) {
setEnvironment("testing/QA")
} else if ( url.includes('flx') ) {
setEnvironment("flx")
}
}, [])
Below an example of an API call from useEffect
const fetchConfigs = () => {
axios({
method: "get",
url: "http://myURL/" + environment + "/WITracker/public/api/myConfigs",
config: { headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "multipart/form-data"
}}
})
.then(function (response) {
setConfigs(response.data);
})
.catch(function (response) {
console.log("Failed to fetch configs!");
addNotification("Unable to fetch configs", "Retry in progress...")
})
}
When remote accessing the users with troubles loading the page, I asked that they each try the alternative browser: Chrome -> Edge or Edge -> Chrome and in each case this resolved the issue. I found this strange as I would have expected the same browser to be causing the same behaviour each time across the users.
I would like to make sure that the page reliably loads for all users regardless of their browser preference. I'm at a bit of a loss trying to find out why only some users are getting unresponsive errors so any possible solutions or suggestions of what to try are welcome!
Possible workaround?
I'm not sure that I have set up my useEffect the correct way using best practices. I'm thinking of adding a slight delay to the API calls, since the page loads the components without issue, and once the delay is up, to synchronously make each of the calls, giving the browser more of a chance to process the smaller chunks of work rather than all at once... please can somebody let me know their thoughts on this?
e.g. Something similar to the below theory?
useEffect(async () => {
// Some delay here, with loading screen
wait(1000) //custom function to wait?
// ...then, update all initial values
await fetchLastUpdated();
await fetchVersion();
await fetchUsername();
await fetchUpcomingFilterOptions();
await fetchLongCustomerNames();
await fetchConfigs();
await fetchUpcomingResults()
...
Thanks in advance

Fetch status 200 but pending endllessly, except first call

I've been searching to solve this problem for a while but couldn't find a working solution.
I'm making a simple social network website and this API returns a article data such as text, image and video url, etc, all saved in server's local MySQL Database. My front-end is React and server is Nginx reverse proxy with Node.js using Express. When I load the page, I create 5 React components that each make fetch request for given article number.
The following code snippet is the fetch API that asks the server to fetch data from database:
//server-side script
app.get('/api/getArticle/:id', (req, res) => {
const con = mysql.createConnection({
host: 'myhost_name',
user: 'myUser',
password: 'myPassword',
database: 'myDB',
});
con.connect(function (err) {
if (err) {
throw err;
}
console.log("Connected!");
})
const idInterest = req.params.id.toString();
console.log(idInterest)
let sql = 'some_sql';
con.query(sql, function (err, result) {
if (err) {
res.status(500).send("Error while getting article data");
return;
}
else {
res.set('Connection', 'close')
res.status(200).send(result);
console.log("ended")
con.end();
return;
}
})
}
//React script
//index.js
fetch('http://mywebsite.com/api/getMaxArticleId/')//Retrieve top 5 article ID
.then((response) => {
for (let i = 0; i < data.length; i++) {
nodesList.push(<Container articleId={data[i]['id']}/>)
}
ReactDOM.render(<React.StrictMode><NavBar />{nodesList}<Writer writer="tempWriter" /></React.StrictMode>, document.getElementById('root'));
})
//Container.jsx; componentDidMount
const url = "http://mywebsite.com/api/getArticle/" + this.props.articleId.toString();
fetch(url, {
method: 'GET',
credentials: "include",
}).then((response) => {
response.json().then((json) => {
console.log(json);
//processing json data
This used to work very fine, but suddenly the getArticle/:id calls started to show 200 status but 'pending' in 'time' column in Chrome network tab, endlessly, all except the first*getArticle/:idcall. This prevents my subsequent .then() in each Container from being called and thus my entire tab is frozen.
Link to image of network tab
As you see from the image, all pending fetches are missing 'Content Download' and stuck in 'Waiting(TTFB)', except the first call, which was '39'
I checked the API is working fine, both on Postman and Chrome, the server sends result from DB query as expected, and first call's Json response is intact. I also see that console.log(response.json()) in React front-end shows Promise{<pending>} with *[[PromiseStatus]]: "Resolved"* and *[[PromiseValue]]* of Array(1) which has expected json data inside.
See Image
This became problematic after I added YouTube upload functionality with Google Cloud Platform API into my server-side script, so that looks little suspicious, but I have no certain clue. I'm also guessing maybe this could be problem of my React code, probably index.js, but I have no idea which specific part got me so wrong.
I've been working on this for a few days, and maybe I need common intelligence to solve this (or I made a silly mistake XD). So, any advices are welcomed :)

How to fix First Character Only bug

I am facing a complex bug where two json fields, the name and the description, only show their first character on a table every now and then randomly for no apparent reason. Has anyone ran into this issue? Attached screenshots of behavior below.
My web stack consists of a golang api get request being called using axios by a react frontend where I feed a react table component.
Table with first character only bug
Table with expected result
Axios Call
fetchMaintenanceEventsData() {
let parent = this;
console.log('Fetching Maintenance Events Data');
this.setState({
maintenanceEventsData: [],
maintenanceEventsDataLoading: true
});
axios.get(`server-status/events`)
.then((res) => {
// console.log('res.data: ', res.data);
parent.setState({
maintenanceEventsData: res.data,
maintenanceEventsDataLoading: false
});
})
.catch((error) => {
console.log("Error:", error);
parent.setState({
maintenanceEventsDataLoading: false
})
});
}
I expect the table fields to display completely 100% of the time.

Reactjs Api Call Not working in Yii2

I'm new to React js And I using Yii2 as my backend..! When I Send a API request to yii2 ,It Returns me the 500 Error.I don't know,Where I made a mistake.
Here is my React Js Code for API call,
fetch('localhost/learning-react/api/admin/signup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
fname:fname,
lname:lname,
email:email,
uname:uname,
passwd:passwd
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson['status']==='1')
{
alert(responseJson['msg']);
}
}
And This is My Yii2 Backend code,
public function actionSignup()
{
//$model = new TblUsers();
return "success";
}
Sorry For my Inability to finding mistakes in my code..!
First of all, 500 means generic server error. So you will need to post your error log as per my comment to help on that. However, I have found your code on the backend is wrong. You do not user restful controller in your code and as such it is not a REST API at all. So I advice you to read through Restful APIs in the Guide. That being said, you basically need to:
Create Restful controller by inheriting from yii\rest\Controller.
Return either Array, DataProvider or instance of yii\base\Model to have guarantee of automated serialization to JSON
so I will show you a simple example to give you an idea. Please read the guide to get in-depth insights on REST API with Yii2.
<?php
namespace app\modules\v1\controllers;
use yii\rest\Controller;
class LoginController extends Controller
{
public function actionSignup()
{
$model = new TblUsers();
//register a user
//return registred user
return [
'success' => true,
'member' => $model;
];
}
}
Let try the following, it may help.
You are making a rest post request, this means two things, first info will travel by POST request, and second dont forget its rest.
try opening the url in the browser, unless you define a rule it should open.
So go ahead open: http://localhost/learning-react/api/admin/signup you should see a "success" on the screen, or you will se the full 500 error printed.
If you were able to open the url on the browser, try the call again, and check your chrome debugger on the network tab. Look for the 500 error open it and read the error, it should be fully printed there on the response tab i.e.
when this is solved, don't forget to enable rules to allow only POST as request, and add the appropriate format for the response so you can consume it as json.
Yii::$app->response->format = Response::FORMAT_JSON;
Hope it helps debuggin.

Spotify API Post Request Add Tracks To Playlist - ERROR 400 BAD REQUEST

Im having what seems to be a very common error when working on the Spotify API adding tracks to a users playlist. In a previous fetch method I have obtained the users playlistId and am now trying to post tracks onto that playlist with that playlistId. I have followed the documentation but am obviously missing something, here is code:
` //userUd, playlistId, currentUserAccessToken, trackURIs are all defined
fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: {
'Authorization': 'Bearer ' + currentUserAccessToken
},
contentType: 'application/json',
method: 'POST',
body: JSON.stringify({
"uris": `[${trackURIs}]`
})
}).then(success => {
return success;
}).catch(err => {
console.log('here is your error', err);
})`
I did the GET request to authorize user - included scope for creating public playlist, in different code block which is working, here's that:
`let scopes = 'playlist-modify-public';
window.location.replace(https://accounts.spotify.com/authorize?client_id=${clientID}&scope=${scopes}&redirect_uri=${redirectURI}&response_type=token);`
Thanks a ton!
The JSON array needs quotes around each element in it. So each track should be quoted, like so:
{"uris": ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"]}
I think you're supplying an object names uris with an invalid array.
And, note you can pass the playlist items as query params too (instead of in the body), without using json. https://developer.spotify.com/web-api/add-tracks-to-playlist/

Resources