Unable to pull through API to react frontend with - node.js

I am struggling to pull through the api to the front end. I completed it successfully with
https://jsonplaceholder.typicode.com/ Just mapped out the arrays. i am struggling however to pull through this seperate api I wanted to use
https://gateway.marvel.com/v1/public/comics?apikey=xxxxxxxxxxxxxxxx&ts=redant&hash=140e85a50884cef76d614f6dacada288
the erro is..
"Uncaught TypeError: Cannot read properties of undefined (reading 'results')"
so clearly it isnt actually able to get hold of results
What am I doing wrong?
import React, {Component} from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
list: []
};
}
componentDidMount() {
fetch('https://gateway.marvel.com/v1/public/comics?apikey=3cb62d086d5debdeea139095cbb07fe4&ts=redant&hash=140e85a50884cef76d614f6dacada288')
.then (response => response.json())
.then(users => this.setState({list:users}))
}
render() {
return (
<div className='App'>
{
this.state.list.data.results.map(result =>
<h1 key={result.id}>{result.urls}</h1>
)
}
</div>
)
}
}
export default App

The error Uncaught TypeError: Cannot read properties of undefined (reading 'results') in your code means that this.state.list.data returns as undefined. This means that you'll need to focus on your state property list to ensure that it has a data property. As we see in your constructor, data is initialized to an empty array which does not contain the data property.
Something we can do to prevent the error is to surround your code with an undefined check:
if (this.state.list.data != undefined) {
this.state.list.data.results.map(result =>
<h1 key={result.id}>{result.urls}</h1>
)
}
At this point, though, we don't know if your API call is returning good data or not since your program throws the error before that (since the fetch and setState are asynchronous), so the code above mainly addresses the error that you're getting rather than focusing on the "pull through the api to the front end" portion of your question.

Here's what you can do inside your then part after fetching the results
this.setState({list:users.data.results}
And inside the map function, do the following:
this.state.list.map(result =>
<h1 key={result.id}>{result.urls}</h1>
You are getting an error because List is initially empty it doesn't have any key called as results, once you fetch the result only then can you loop through your result.
Another solution would be to simply add a loader, you can control that via state as well.

Related

React state data changing on its own

Hi I'm working on a simple address book app made with ReactJS.
There's one boolean key in state called 'show_personal'. By default it is set to false. When it is true then the component will render personal address book.
For some reason this boolean value keeps changing on page reload. I've put some logging statements which shows value of it.
I noticed that almost in a sec when the component gets rendered, its value changes due to which my component get re-rendered and this breaks my app UI.
I'm using proper way to update state using this.setState method. While logging/debug I've disabled every possible function which toggles this value. Still facing this issue
Is there anyway to trace which component of code has changed it's value ?
class Home extends React.Component{
state = {
show_personal : false
}
render(){
const checkFlag = ()=>{
if(this.state.show_personal){
return <div>Show personal records</div>
}
}
else{
return <div>Show business records</div>
}
return({
{checkFlag}
})
}
}
Hi your render syntax is a little unusual, you return your checkFlag function without calling it, I don't known what that could do...
Maybe you could try it like this to see if it behaves better
class Home extends React.Component{
state = {
show_personal : false
}
render() {
return this.state.show_personal ? <div>Show personal records</div> :
<div>Show business records</div>
}
}

"Cannot read property 'map' of undefined" react and node.js

https://github.com/dongha1992/MERN-boilerplate
enter image description here
hello. currently I tried to practice shopping mall clone as react and node.js
I faced that problem I attached. it doesn't seem that error for cos I copied same as tutorial but it is something wrong with node.js(localhost:5000)
I tried to everything to fix it but don't know how to approach. please help me!
enter image description here
Probably an asynchronous request that populates your props.images hasn't returned a response.
Prefix props.images && to props.images.map function
That way only when the prop is present does the the map occur. Like this
{props.images && props.image.map(image=>.........
Ok, this is often an issue of a variable taking on different value during code execution. To safeguard again this, it's recommended to make sure that the props or a specific variable is defined before it's used.
// alternative-1
function ImageSlider(props){
return props.images && (
<div>
<Carousel autoplay>
{props.images.map((image, index) =>
// ...
)}
// ...
</div>
);
};
OR
// alternative-2
function ImageSlider(props){
return props.images ? (
<div>
<Carousel autoplay>
{props.images.map((image, index) =>
// ...
)}
// ...
</div>
) : null;
};
Critically, here's what is happening in the return() statement.
Alternative-1 (Implicit):
The second part, <div> is only rendered if the first part is true.
In core JavaScript, undefined is equivalent to false so props.images is true only when images is !undefined (not undefined; in other words, images is defined).
Alternative-2 (Explicit):
This one is more direct, as long as props.image is undefined, we return null.(Remember, a valid react component must return something. If nothing, then return null)
Only when props.images is defined, then we return the <div>.
These added checks ensure that your code never breaks, in this case your map() will always be called on a defined variable (props.images).
Here's a good read on Conditional rendering from the react team.
It looks like you're trying to call the map function on data that hasn't been received from your axios request. You should add some logic so that any components that rely on your request data render only if it exits, easily done with a ternary operator.
It looks like many components (including imageSlider) depend on data you try to access when you call your renderCards function on line 54 of your App.

How to setState of redux wrapped component?

I'm trying to test a component that is wrapped in Redux:
beforeEach(async () => {
component = await mount(
<Provider store={buildStore()}>
<CheckoutOverlay cartItems={basicCart} />
</Provider>
)
await component.update();
})
Things I've tried:
component.find(CheckoutOverlay).instance().state.coupon={} (Cannot read 'state' of null)
component.find(CheckoutOverlay).state.coupon={mode:0, value:.25}; (state does not update)
component.find(CheckoutOverlay).setState({coupon: {mode: 0, value: .25}}); (setState() can
only be called on class components)
component.find(CheckoutOverlay).instance().setState({coupon: {mode: 0, value: .25}}); (cannot read property 'setState' of null)
I've also tried some suggestions that use SHALLOW() and .dive(). But I always get the error 'dive()' is not a function. I am using Enzyme 3.11.0
How can I update the state of a component wrapped in the Redux Provider?
Additional Info:
Inside my component, CheckoutOverlay, I have another component that calls a function in CheckoutOverlay. This function stores the data sent in the State.
I am trying to simulate what happens when the data is sent to CheckoutOverlay.
The sub component has tests, and, I suppose, I can do something like simulate the click on that component. But that seems like it is more involved than it should be.
Since you have not mentioned what you are trying to test, I am giving you some general suggestions.
You should not test the implementation details, rather test the functionality.
If your state is dependant on the redux store state, you can pass the required data as initialState to your provider.
You cannot use instance on a functional component

Error:Element type is invalid: expected a string (for built-in components)or a class/function(for composite components)but got:object

import React from 'react'
const Newslist=(props)=>{
const Items = props.news.map((item)=>{
return (<h2>{item.title}</h2> )
});
return(<div> <Items/> </div>)
}
export default Newslist;
This piece of code is not displaying anything in the dom and showing the error
Error:Element type is invalid: expected a string (for built-in components)or a class/function(for composite components)but got:object
You're rendering Items as if it were a React component and not a JSX variable. As the error says, React components can only be created from strings (in the case of HTML elements), classes or functions. When you render something using the <JSX/> syntax it is passed as an argument to React.createElement. An array of JSX elements, which is what your map call returns, is not one of the accepted parameter types, so you are getting this error. I think this should work:
import React from 'react'
const Newslist=(props)=>{
const items = props.news.map((item)=>{
return (<h2>{item.title}</h2> )
});
return(<div> {items} </div>)
}
export default Newslist;

Call LitElement method from outside the element

I have a simple LitElement component like so:
class MyElement extends LitElement {
constructor() {
super();
}
customMethod(data) {
// do something with the passed parameter
}
render() {
return html`<div id="element"></div>`;
}
}
customElements.define('my-element', MyElement);
And I want to be able to call that customMethod from outside of my element.
So for example if I add the element to web page like so:
<my-element></my-element>
I then want to be able to add some JavaScript to the page and call that customMethod.
I tried:
var element = document.getElementById('element');
element.shadowRoot.customMethod('example data');
But it claims it's not available... How can I call a method on an instance of LitElement?
You don't need to use shadowRoot in the call :
var element = document.getElementById('element');
element.customMethod('example data');
but you need to be able to locate your element
<my-element id='element'></my-element>
I had a very similar problem and the existing answers did not seem to fix it. The reason for my issue was caused by the fact that LIT Element scripts are exported as modules, meaning that they are loaded and executed after the initial DOM has been parsed. So if you are using a script to access the public method - make sure that it is also in a module (or you can alternatively place the code into an appropriate timeout).
So when defining an element in LIT Element as follows:
#customElement('my-element')
export class MyElement extends LitElement {
#state()
text = '';
customMethod(data) {
this.text = 'Custom method was called!';
}
render() {
return html`<div id="element">${this.text}</div>`;
}
}
And adding a script in my index.html page:
<my-element id='element'></my-element>
<script type="module">
const element = document.getElementById('element');
element.customMethod();
</script>
Make sure that the script tag contains type="module". Otherwise you will see the following error in the console: Uncaught TypeError: element.customMethod is not a function
Link to LIT Element Playground.
Also, here is a great article that explains how scripts are loaded in detail.

Resources