TypeError: device.devices.map is not a function - node.js

I put products on the page and then I got an error, I can't figure out who this is connected with.
const {device} = useContext(Context)
91 | </div>
> 92 | <div className="inner-display-collection">
| ^ 93 | {device.devices.map(device =>
94 | <CartGoods device={device}/>
95 | )}
the product itself:
const CartGoodr = ({device}) => {
const history = useHistory()
return(
<div className="inner-display-collection">
<a key={device.id} href="" className="active-cart" onClick={() => history.push(DEVICE_ROUTE + '/' + device._id)} style={{textDecoration: 'none'}}>
<div className="cart-good">
<div className="wrapper-cart">
<img className="foto-cart" src="" alt="" />
<div className="display-info-cart">
<h3 className="text-price-cart" >{`${device.prise}₽`}</h3>
</div>
<div className="display-info-cart">
<h4 className="text-decription-cart">{device.descriptionMine}</h4>
</div>
</div>
</div>
</a>
</div>
)
}
export default CartGoodr
that is, everything should work out, but this error crashes

The problem is that your device.devices object is empty. It must be an array to have access to that .map function, because it is only accessible on the arrays.
If you try to console log device.devices right before mapping elements, then you will see that it outputs rather undefined, null, number or string instead of array
const {device} = useContext(Context)
console.log(device.devices) // here
If that data is fetching through api request then you could add loading property to the device, set it to true before making the API request and when the data is fetched set it to false, then use it like so:
if(device.loading){
return <p>Loading the device...</p>
}
// and here map through the device.devices or any other content of your component

Related

this code setting all post to true react js

const likeHandler = (index) => {
const allData = [...urls]
const getMatchingImage = allData.find((_item, i) => i === index);
const getMatchingImageIndex = allData.indexOf(getMatchingImage)
if (index === getMatchingImageIndex) {
setLike(true);
}
console.log('key index handler', index);
console.log('key index getMatchingImage', getMatchingImage)
console.log('key index getMatchingImageIndex', getMatchingImageIndex)
}
<div className={styles.imgContainer}>
{urls.map((url, index) => (
<Box key={index}>
<div className={styles.postHeading}>
<img src='https://placehold.co/70x70' alt=''/>
<div className={styles.postUserName}>Dinesh Kumar</div>
</div>
<div className={styles.imgContainer} style={{backgroundImage: `url(${url})`}}></div>
<div className={styles.actionButtons}>
<div>
{!like ?
<AiOutlineHeart onClick={() => {likeHandler(index)}} className={`me-2`}/> :
<AiFillHeart onClick={() => {unLikeHander(index)}} className={`me-2`} />
}
<AiOutlineMessage className={`me-2`}/>
<FiSend className={`me-2`}/>
</div>
<div>
<FiBookmark/>
</div>
</div>
</Box>
))}
</div>
I am working on post like functionality when I likes a particular post it liked all post. I am consoling all information. Please have a look
I am working on post like functionality when I likes a particular post it liked all post. I am consoling all information. Please have a look
I am working on post like functionality when I likes a particular post it liked all post. I am consoling all information. Please have a look
You should declare the like property as an array of boolean and toggle the values referring to the element with index:
const [like, setLike] = useState(new Array(urls.length).fill(false));
...
const likeHandler = (index) => {
const allData = [...urls];
const getMatchingImage = allData.find((_item, i) => i === index);
const getMatchingImageIndex = allData.indexOf(getMatchingImage);
const updatedLikes = [...like];
updatedLikes[index] = true;
setLike(updatedLikes);
};
...
<div>
{!like[index] ? (
<AiOutlineHeart
onClick={() => {
likeHandler(index);
}}
className={`me-2`}
/>
) : (
<AiFillHeart
onClick={() => {
unLikeHander(index);
}}
className={`me-2`}
/>
)}
<AiOutlineMessage className={`me-2`} />
<FiSend className={`me-2`} />
</div>
It's better to use classes. instead of styles. This is such a conditional standard when you use .module.css
Instead of
<div className={styles.imgContainer}>
better this way :
<div className={classes.imgContainer}>

i cant see to find the solution to this REACT

I'm new using react and I don't understand this issue I'm getting.
`Compiled with problems:X
ERROR in ../src/JwModal.jsx 105:12
Module parse failed: Unexpected token (105:12)
File was processed with these loaders:
./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| render() {
| return (
<div style={{display: + this.state.isOpen ? '' : 'none'}} onClick={this.handleClick} ref={el => this.element = el}>
|
| `
I saw a post where they say to check file location at the same number it tells you.
this is line 102 - 113
render() {
return (
<div style={{display: + this.state.isOpen ? '' : 'none'}} onClick={this.clickNode} ref={el => this.element = el}>
<div className="jw-modal" style={this.styles.modal}>
<div className="jw-modal-body" style={this.styles.body}>
{this.props.children}
</div>
</div>
<div className="jw-modal-background" style={this.styles.background}></div>
</div>
)
}

Uncaught TypeError: data.map is not a function. react functional component

I extracted array from object by using results.post still it says data.map is not a function.
fetch('/allpost',{
headers:{
"Authorization":"Bearer "+localStorage.getItem("jwt")
}
}).then(res=>res.json())
.then(result=>{
console.log(result.posts)
setData(result.posts)
})
},[])
return (
<div>
{
data.map(item=>{
return(
<div className='home-container'>
<h5 className='home-name'>salil</h5>
<div className='card-image-container'>
<img className='card-image' alt="blank" src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8d2FsbHBhcGVyJTIwbmF0dXJlfGVufDB8MHwwfHw%3D&auto=format&fit=crop&w=500&q=60" />
</div>
</div>
)
})
}
</div>
);
};
export default Home;
can someone tell me whats the error I made here?
First, when the 'useState' is declared, should define the types and assignments. Like this const [data,setData] = useState<Array<T>>([]);.
Secondly, fetch api,we should confirm what type we want, like .then(result=>{ setData(result?.posts || []); }). that mean if 'result?.posts' is underfind, we can save [].
Finally, we should process the different types of data at render
function _demo() {
return (
<div>
{data?.length === 0 && (
<div>
<span>Loading, Please Wait</span>
</div>
)}
{data?.length > 0 && data?.map((v)=> {
return (
<div>
</div>
)
)}
</div>
);
}

Computed variable is undefined after button click

Full code: https://github.com/kenpeter/test_vue_simple_audio_2
In Main.vue
I tried to assign new value to this.player.currentTrack, by following this guide.
selectTrack: function selectTrack(id) {
this.player.currentTrack = Object.assign(
{},
this.player.currentTrack,
{ currentTrack: id },
);
this.player.elapsed = Object.assign(
{},
this.player.elapsed,
{ elapsed: 0 },
);
// this.play();
},
It seems no error, until I click the button
Error: Cannot read property 'duration' of undefined
In Main.vue, currentTrack.duration
<div class="player__timer">
<div class="player__timer__elapsed" v-text="player.elapsed"></div>
<div class="player__timer__total" v-text="currentTrack.duration"></div>
</div>
<div class="slider player__progress-bar">
<input type="range" :value="player.elapsed" :max="currentTrack.duration" />
</div>
From the image, you can see that there is a value: 274, which is the value of currentTrack.duration initially. After I click the button, currentTrack becomes undefined. currentTrack is a computed value.
You used currentTrack.duration instead of player.currentTrack.duration, try this:
<div class="player__timer">
<div class="player__timer__elapsed" v-text="player.elapsed"></div>
<div class="player__timer__total" v-text="player.currentTrack.duration"></div>
</div>
<div class="slider player__progress-bar">
<input type="range" :value="player.elapsed" :max="player.currentTrack.duration" />
</div>
this is the correct way to do object.assign. My method above is wrong.
let player = {
currentTrack: 0,
other: ""
};
console.log(player);
player = Object.assign(
{},
player,
{ currentTrack: 2}
);
console.log(player);

Cannot use $(this) in $.getJSON in .each

Im building a custom Minecraft Server Status and hit a problem. The first version of this was successful but the code was rather long and I decided to make it better and shorter. The script is supposed to fill the elements of each .server but it doesn't work.
<div class="server_status">
<div class="container servers_info">
<h1>My Network</h1>
<div id="of the server" class="server" title="of the server" server-ip="0.0.0.0">
<div class="name"></div>
<div class="count"><i class="fa fa-spinner fa-spin"></i></div>
<div class="players">Loading player data <i class="fa fa-spinner fa-spin"></i></div>
<div class="status"></div>
</div>
<div id="of the server" class="server" title="of the server" server-ip="0.0.0.0">
<div class="name"></div>
<div class="count"><i class="fa fa-spinner fa-spin"></i></div>
<div class="players">Loading player data <i class="fa fa-spinner fa-spin"></i></div>
<div class="status"></div>
</div>
<!-- ..... more servers -->
<span class="total"><i class="fa fa-spinner fa-spin"></i></span>
</div>
$(document).ready(function ping() {
$( ".servers_info .server" ).each( function() {
var name = $(this).attr( "title" );
var ip = $(this).attr( "server-ip" );
var id = $(this).attr( "id" );
var total = 0;
var call = "Get Avatar List adress";
//Set the name:
$(".name",this).html(name);
//Gets the data:
$.getJSON("http://mcapi.ca/v2/query/info/?ip=" + ip, function (json) {
//Checks The status and applies visual effects:
if (json.status !== "false") {
$(".status",this).html("<span class=\"l-online\">" + json.ping + " ms</span>");
$(this).removeClass('blur');
} else {
$(".status",this).html("<span class=\"l-offline\">0 ms</span>");
$(this).addClass('blur');
};
});
});
//Sets Refresh rate of 10s
setTimeout(ping, 10000);
});
I narrowed down the problem to the $.getJSON part. The data is retrieved correctly but cannot be placed in its respective DIVs. The only difference with the first version of the script is that I used 4 getJSON separately for each of the servers I wanted to display. Now using .each to combine it for all 4 of them and also $(this) to use relative objects.
I suspect the problem is in th usage of $(this) in .get but I'm nnot sure and don't know how to fix it.
As you suspect, the issue is the $(this). part. Inside the $.getJSON callback this no longer refers to the DOM object that triggered the event.
To fix this you can either:
Add a .bind(this) to the callback function. No changes required inside the function itself.
$.getJSON(url, function(json) {
/* all your code here */
}.bind(this)
);
Or save the reference to this before $.getJSON and use it inside the callback.
var _this = this;
$.getJSON(url, function(json) {
/* replace all references of this to _this for example*/
$(_this).removeClass('blur');
});
Hope that helps

Resources