Localhost:3000 not displaying anything after changing code - javascript

I'm following along a javascript tutorial, and suddenly localhost:3000 is not displaying anything but a white page after making some changes in my About.jsx file.
It started happening after I added:
import { urlFor, client } from '../../client';
and
const [abouts, setAbouts] = useState([]);
useEffect(() => {
const query = '*[_type == "abouts"]';
client.fetch(query)
.then((data) => {
setAbouts(data);
})
}, []);
If I undo the changes, hit save after adding one change at a time, it's fine. But once all of them are in place, Chrome doesn't display anything.
I've tried adding an error in my code to see what happens, and the browser immediately picks up on it displaying it in red, so apparently it's not NOT working.
Any idea what's happening? I've also tried deleting all cookies/browser history/caches with no luck.
EDIT:
Tested a bit more now, and it really seems like the import is the culprit here. I followed the tutorial to a t, but one thing that puzzled me was that I have no folder called client. It's a client.js file inside my src folder, but that's what the tutorial dude did, and so far in the video it still works for him, so... still confused.
My client.js file looks like this:
import sanityClient from '#sanity/client';
import imageUrlBuilder from '#sanity/image-url';
export const client = 'sanityClient'({
projectID: process.env.REACT_APP_SANITY_PROJECT_ID,
dataset: 'production',
apiVersion: '2022-02-01',
useCDN: true,
token: process.env.REACT_APP_SANITY_TOKEN
});
const builder = imageUrlBuilder(client);
export const urlFor = (source) => builder.image(source);

I found the error, and now I'm deciding between jumping for joy or just jumping into a lake, lol.
Apparently, it IS a big deal if you write 'projectID' when it should be 'projectId'..!
Who knew! Happy Saturday, everyone :)
EDIT: And I had to remove the '' from
export const client = sanityClient({
I thought about deleting this question since I figured it out myself, but maybe this will be to some help for anyone else sometime, so I'll leave it up.

Related

ReferenceError: Element is not defined (Object.<anonymous>) in Intro.js-react, React, Next.js and Tailwind CSS

Code is like here.
import { useState } from 'react';
import { Steps } from 'intro.js-react';
export default function Dashboard() {
const [stepEnabled, setStepEnabled] = useState(true);
const steps = [
{
intro: 'Welcome to WorkStats!'
}
];
const onExit = () => {
setStepEnabled(false);
};
return (
<main>
<Steps
enabled={stepEnabled}
steps={steps}
initialStep={0}
onExit={onExit}
/>
<div>Test</div>
</main>
);
}
An error is like this.
This error is similar to this issue NextJs: Element is not Defined when using Intro.js but it did not work for me.
As you can see in the attached screenshot, the error is saying that it is because an element is not defined in the Object.<anonymous>.
This Object.<anonymous> is <Steps>. Comment this out, because if you comment it out, the error goes away. And <Steps> is imported from intro.js-react. And intro.js-react is indeed already installed, as shown in the attached third screenshot below.
Let's look a little more inside the node_module as mentioned in the error message. In the attached third screenshot, if you look at line 310, character 110, you will see that there is indeed an Element. According to the attached first error message, this is not defined. I do not know why this is.
The step.element in this <Steps> is not isRequired. I don't understand why they say that Element is not defined.
By the way, I get this error when I reload, but once I comment it out and reload it again, it displays correctly. If I uncomment out the commented out section again after this, the intro.js-react pops up correctly. I think this is another hint, but I don't know why.
I updated the next day.
Modified code as below, which resolved the original error.
import { useState } from 'react';
import dynamic from 'next/dynamic';
// import { Steps } from 'intro.js-react';
// Newly added
// #ts-ignore
const Steps = dynamic(() => import('intro.js-react').then((mod) => mod.Steps), {
ssr: false
});
export default function Dashboard() {
const [stepEnabled, setStepEnabled] = useState(true);
const steps = [
{
intro: 'Welcome to WorkStats!'
}
];
const onExit = () => {
setStepEnabled(false);
};
return (
<main>
<Steps
// #ts-ignore
enabled={stepEnabled}
steps={steps}
initialStep={0}
onExit={onExit}
/>
<div>Test</div>
</main>
);
}
Then the original error "Element is not defined" was gone but the problem still existed. The problem is like this.
https://www.loom.com/share/22a307b2221f42d5b3548647f5da23fc?t=5
The screen darkened for a moment and there was a feeling that a pop-up might appear, but it quickly brightened, and eventually, no pop-up appeared.
If you look at the console log, you see that something appears and disappears for a moment. Here is a screenshot of that moment. It is hard to see, but it still looks like a popup caused by Intro.js-react.
Here's what it looks like when zoomed in.
However, if you look at it carefully, you will see that both top and left, which probably specify the position, are 0px, and width and height, which may be the width and height of the popup, are also 0px. It looks as if nothing will show up on the screen. I don't know why these values are set.
After modifying one more part of the code, the popup finally appeared without any errors.
Before
const onExit = () => {
setStepEnabled(false);
};
After
const onExit = () => {
setStepEnabled(true); // Changed from "false" to "true"
};
However, I am unclear why this worked. Since it is unclear, I was able to avoid the error in front of me, but I cannot apply it in the future. I would like you to continue to tell me why.
https://www.loom.com/share/a88fa3e835a44986889664151f030bfe
As a minor but important detail, I only defined three steps, but there were four... What the heck is the second pop-up, there is one mysterious step.

Build System CTA's/Callback function not working

I am working on a build/design system. and everything works fine. The only issue is when I publish my package and attempt to use the callback function. It doesn't properly return the data that is necessary for me to go to the next screen.
I attempted to get a reproducible example for you in CodeSandbox, however, there were some minor implications/errors that wouldn't allow me to get to the specific error I am talking to you about now. That seems to have its own issues.
So, how do you reproduce this error? Well, our package as of right now is public. As said above you can't import into CodeSandbox as it gives other errors on React versions (as said, I will deal with that later..). The package name is #sandboxcommerceeng/react the scss package you might need is #sandboxcommerceeng/scss. Go ahead and import into a CSS file. #import '#sandboxcommerceeng/scss/lib/global.css'. Then in the #sandboxcommerceeng/react package, import ECommercePlatformModal. The code below will give you a reproducible error. Platforms type, is also exported by #sandboxcommerceeng/react
const [showEcommerceModal, setShowEcommerceModal] = React.useState<boolean>(false);
const [url, setUrl] = React.useState<string>('');
const [selectedPlatform, setSelectedPlatform] = React.useState<keyof Platforms>();
<ECommercePlatformModal
selectedPlatform={selectedPlatform}
onSelectPlatform={(platform: keyof Platforms | undefined) =>
setSelectedPlatform(platform)
}
showModal={showEcommerceModal}
onCancel={() => setShowEcommerceModal(false)}
okButtonProps={{ onClick: () => console.log(url) }} // ✴
urlValidated={true}
onUrlChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setUrl(e.target.value);
}}
url={url}
/>
✴: I am unable to get the URL from the state using a callback. I've tried just referencing a callback function separately and then logging the URL from there. I've also tried pasting in the URL from the callback. Nothing is working.
End Goal
The end goal here is to have it so that I am able to apply my package into my React application and have the package functionality, i.e. the javascript code implemented in the package itself, work as expected. Expectation for this particular component, is to be able to console.log the url and have it show in the package from the callback function okButtonProp{{onClick: () => console.log(url)}}
Please let me know if there is anything else you need from me.
Your answer lies here. (it could be just a comment but don't have enough reputation yet :) ).
After debugging, the issue did lay within the build system itself. Using React.memo on a button component was the culprit. The memoization wasn't working as intended due to the fact that none of the props were actually changing on the component, therefore it wasn't re-rendering the button component with the new function and variables being passed down to it.
I went ahead and removed the memoization from the memoized component, as I couldn't see a way to fit memoization in this instance.

Having trouble with persisting React state using localStorage with a SSR (Next.js) app

The app I'm making has customizable settings. I'd like to load default settings, then when a user makes any changes, the custom settings will be stored in localStorage. Now the next time a user comes back, we'll load the setting from their localStorage.
I'm using React context like so...
const SettingsContextProvider = (props: any) => {
const [settings, setSettings] = useState(getSettings());
useEffect(() => {
localStorage.setItem('settings', JSON.stringify(settings))
}, [settings]);
return (...some jsx...);
}
Then getSettings()...
getSettings() {
// get from local storage
if (process.browser) {
const localSettings = localStorage.getItem('settings');
if (localSettings) return JSON.parse(localSettings );
}
// fall back to default settings
return "Something else";
}
The issue I'm having is that the server side load (on the node side), we don't have local storage (which is why I check for process.browser), so it falls back to default settings. THEN when it gets to the browser, it seems to call getSettings() again, in which case we DO have local storage and it loads from there.
That works, but then I get an error:
Text content did not match. Server: "Something else" Client: "Something custom"
So I understand that the server isn't matching the client and it's upset about it. I get WHY it's happening, but I have NO IDEA how to fix it. Maybe I need to implement reducers or use cookies?
Has anyone come across this?
I'm more than happy to share my full repo code if it'll help.
I'm fairly comfortable with react but have pretty much NEVER used react hooks in my own code.
However, I feel like I wouldn't put the updating of the localStorage into a useEffect function like that (and I could be totally wrong about that).
So, first, I would check that that useEffect function is being called when you're expecting it to be.
And then, I would write a function
const updateSettings = (newSettings) => {
localStorage.setItem('settings', JSON.stringify(newSettings))
setSettings(newSettings);
}
And use that updateSettings function to pass down to components.
BUT, I could be totally off there, like I said I don't use react hooks and only have a theoretical understanding.

Can I use axios in this example?

I'm still new to web development so I'm really sorry if the answer is obvious or the information provided by me is not much, but I hope this is sufficient:
Can I make an axios.post request within this vue.js component?
<script>
module.exports = {
mounted() {
// game code
};
</script>
Let me explain the problem I'm having at this moment: I can't import axios by import axios from "axios";. I neither can use export default { ... }. Both result in the page not loading (giving me an TypeError: "exports" is read-only). However, I need to access a variable within the gamecode since I want to axios.post that said variable (game score plus some more json info) to my MongoDB database.
If I can't make the request from there, am I able to get a variable from that code in mounted() { // game code }; and pass it to another component (and post it from there)? I searched the Internet for many hours but nothing seems to work for me, so again, sorry if it seems like I'm just too lazy to search for answers.
I managed to use axios within the module.exports part of the code.
Normally I would use import axios from 'axios'; and use axios as a method within
export default {
...
methods: {
// here (axios method)
...
But the
module.exports = { mounted() {
// game code
};
part did not work if I used the export default code part. I'm almost sure there is a more elegant way to solve this whole problem, but since I'm new and still don't understand totally how Vue and axios works, I simply tried some possibilities to include axios there and one worked:
module.exports = { mounted() {
const axios = require("axios");
// game code
// and later, for example: axios.post(...)...
};
At first I thought it wouldn't work since my IDE did not recognize the axios methods, but it actually posted data to my DB, so it did work.

Ionic + Firebase - Real time database not updating view

I have a really weird problem with my application. In order for the real time database to display, I have to interact with the application. 2 months ago I did not have this problem, the information appeared normally, but now, I have to click on a button or something in order for the view to update.
I made a quick GIF here:
If you pause just as I click the <- back button you'll see what I mean.. https://i.gyazo.com/44b450aa502dc7f37e5a5feea19824c6.mp4
I don't know what I did to make this happen..
Here is a code example from my application:
.ts:
if(fromClick) { this.subscription.off(); }
this.postFeed = new Array();
this.subscription = this.database.database.ref('/posts/'+this.locationId)
.orderByChild('score')
.limitToLast(10);
this.subscription.on('child_added', (snapshot) => {
this.postFeed.push(snapshot.val())
});
.html:
<ng-container *ngFor="let post of postFeed.reverse(); let i = index">
<post [postData]="post"></post>
</ng-container>
So this code above used to work perfectly, but now I have to interact with my app for it to display on the screen, even though the postFeed console logs perfectly fine. The data shows up in the console exactly when I request it, but it doesn't show on screen.
Any ideas? As I said, it used to work fine. Any help would be great! Thank you
For anyone else who has this problem, NgZone was the answer for me.
I imported it:
import { NgZone } from '#angular/core';
added it to the constructor:
public zone: NgZone,
and then wrapped it around my firebase code:
this.zone = new NgZone({});
if(fromClick) { this.subscription.off(); }
this.postFeed = new Array();
this.subscription = this.database.database.ref('/posts/'+this.locationId)
.orderByChild('score')
.limitToLast(10);
this.subscription.on('child_added', (snapshot) => {
this.zone.run(() => {
this.postFeed.push(snapshot.val())
}):
});
and this worked wonderfully for me. I couldn't find the actual cause of the issue, but I just wrapped the NgZone code around all my firebase functions and it worked like it used to. If anyone else has more information that would be great.

Categories

Resources