React Starter Kit error - page not found - reactjs

I created a new route from the react-starter-kit project and it does an async fetch of some data, then renders it, but a second later the page reloads with a message saying "Page not found - sorry but the page you're trying to view does not exist".
In the console I see - "Warning: Text content did not match. Server: "Balances" Client: "Page Not Found"
async function action() {
let bittrex = new ccxt.bittrex ({
'apiKey': '',
'secret': ''
})
try {
// fetch account balance from the exchange
let bittrexBalance = await bittrex.fetchBalance ()
/**** commenting above and uncommenting this block stops it from happening....
let bittrexBalance = {};
bittrexBalance.info= [];
let currency = {};
currency.Currency = "BTC";
currency.Value=999;
// output the result
bittrexBalance.info.push(currency);*/
console.log ('balance', bittrexBalance)
let balances = [];
balances.push(bittrexBalance)
return {
title: "Balances",
component: (
<Layout>
<Balances balances={balances} />
</Layout>
),
};
} catch (e) {
console.log('SOME sort of error', e);
}
Does anyone have any idea what this could be?
Edit to add, I realise now that if I disable Javascript everything works perfectly...
It seems to be running through the universal router twice. The first time
That's the only clue I've found so far... I don't understand why it's reloading the page once it has already loaded...
The Page not found error is coming from it going through :
catch (e) the second time... I suspect something is happening inside the ccxt library but that the problem is actually that it is called a second time because the page is somehow reloaded...

It seems you have to call await bittrex.loadProducts() before fetching your Balance.
Edit : Seems also that bittrex.loadProducts() has been renamed by bittrex.loadMarkets()
More info in this issue on github

Your server code reached exception, which turns into rejection of route, because action method returns undefined, so server will fall down through —
next routes will not fit and finally it reaches the not found route.

Related

Error handling response: Error: Blocked a frame (...) from accessing a cross-origin frame

I am fetching a calendly embed link dynamically into a next.js13 app, and technically, it is working. However, sometimes the embed doesn't fetch, resulting in a screen that looks like this:
ONLY upon refresh, the embed populates, and the console shows the error:
After doing some research, it seems as though this could be a CORS issue, though I am not sure. The way the embeds are pulled in is from supabase, through a fetch function and then passed to the static page like so:
export default async function HostPage({
params: { username },
}: {
params: { username: string };
}) {
const { data: profile } = await supabase
.from("profiles")
.select()
.match({ username })
.single();
const [host] = await Promise.all([profile]);
return (<div
data-url={profile.calendar_embed}
></div>)
To recap:
Sometimes, the embed gets fetched and displays right away. Errors are shown in the console
Some other times, the page remains empty, no errors in the console.
Upon refresh, the embed appears, with errors in the console.
Does anybody have an idea and can point me in the right direction?
Thanks in advance.

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

React-Native unable to store state getting null

I'm new to React-native so if there is a misunderstanding please be super clear and treat me as if I have never seen React-native before.
I have the app so that when you press on a button it will send you into an Auth0 flow where you can log in to the app. This seems working. If I log out the access token directly in the callback I am successful in getting it at the credentials.accessToken variable/location. However, when I am trying to set the state of the accessToken variable I get back null when I try to log it out to the screen via an alert or even via console.log. What am I doing wrong to cause this? I tried searching SO and google but both seem to show this as the right way of doing it.
Code:
const [accessToken, setAccessToken] = useState(null)
const onLogin = () => {
auth0.webAuth
.authorize({
scope: 'openid profile email'
})
.then(credentials => {
setAccessToken(credentials.accessToken)
Alert.alert('Access token: ', accessToken)
})
.catch(error => console.log(error)) // Eventually send this to backend for crash reporting
}
This is probably a case of a state not updating immediately. Try to use a useRef() instead of a useState(https://www.w3schools.com/react/react_useref.asp). If the problem is solved the issue was with the fact that states are updated asynchronously and hence it was not set to its most recent value (the value you expected) when you console logged it.

React APP makes a ton of API Calls and crashes

I am making a simple app that makes an api request to my local server and gets some data and puts it on a chart from trading view. This should be pretty simple as everything is just for practice, but when I change some of the values on my server and make the call, the app keeps making the call like 35 times before the server crashes and then the app just says
"net::ERR_CONNECTION_REFUSED"
and doesn't display the data as it should.
This is the whole code, it has two parts. One parts makes the call to get example data of name and another call to get example data that will go to the chart (the second part is the issue.)
This is the code just for the second part:
getBars: async (
symbolInfo,
resolution,
periodParams,
onHistoryCallback,
onErrorCallback
) => {
try {
if (resolution === '1D') {
resolution = 1440;
}
const response2 = await axios.get('http://localhost:8000/chart');
console.log('got bars data');
const bars = response2.data.map((el) => ({
time: new Date(el.timeInterval.minute).getTime(), // date string in api response
low: el.low,
high: el.high,
open: Number(el.open),
close: Number(el.close),
volume: el.volume,
}));
if (bars.length) {
onHistoryCallback(bars, { noData: false });
} else {
onHistoryCallback(bars, { noData: true });
}
console.log('bars done');
} catch (err) {
console.log({ err });
}
};
So what happens is that the console.log "got bars data" and "bars done" repeats many times until my localhost:8000 server crashes and then the app gives the error I showed above, because of this it doesn't display the data. I have no Idea why this may be happening,
This is what the data looks like for the one that does not works:
{"timeInterval":{"minute":"2022-03-14T23:45:00Z"},"volume":0.05,"high":3.910209183178435e-9,"low":3.910209183178435e-9,"open":"3.910209183178435e-09","close":"3.910209183178435e-09"}
This is for the one that works:
{"timeInterval":{"minute":"2022-03-17T15:00:00Z"},"volume":0.05,"high":0.00001255389794727055,"low":0.00001255389794727055,"open":"1.255389794727055e-05","close":"1.255389794727055e-05"}
I would appreciate any help, thanks!
EDIT
I just noticed, with the data set that works, console.log('got bars data') and console.log('bars done') don't occur for some reason, but the data still shows up on the chart even though the console doesn't log.

UserEvent doesn't wait for dialog to be loaded when it is lazy load

After updating testinglibrary/userEvent from version 13 to 14, it is not waiting for dynamically rendered.
My dialog is lazily loaded as well as the content inside the dialog.
An example code is below.
it('updates the channel information after edit channel request succeeds', async () => {
render();
await userEvent.click(await screen.findByTestId('TestId'));
const myDialog = await screen.findByRole('dialog');
// This is problematic.
const nameField = within(myDialog).getByLabelText(/name/i);
})
Dialog shows spinner until it finishes fully loading the content.
And the content will be rendered as long as query waits. But it doesn't wait for the content to be rendered but quits waiting as soon as it finds the spinner, saying it couldn't find the content but only spinner.
What I tried
Using find query instead of get, some tests are resolved only doing this but others aren't.
Using screen instead of within(dialog).findBy. This resolves some breaking test as well.
I looked over the document and changelog if there were effective change that possibly breaks the test code, but had no luck :(
What should I do with it?
This might be because you haven't ran setup yet. userEvent's API have changed in 14, and now, per the documentation:
We recommend invoking userEvent.setup() before the component is rendered.
So in your case, you need to try something like this.
it('updates the channel information after edit channel request succeeds', async () => {
const user = userEvent.setup()
render();
await user.click(await screen.findByTestId('TestId'));
const myDialog = await screen.findByRole('dialog');
// This is problematic.
const nameField = within(myDialog).getByLabelText(/name/i);
})

Resources