Reputation: 35
i'm very new to react.js and i got a question about my program. I am getting a type error when i try to invoke a method when the corresponding buttton is clicked. Basically the method generates a random number and i want to display this number in another component. For this to work i have to write the return in the variable 'defNum' located in the object state. I hope you can help me :)
My Code in the context.js:
defaultNumber = () => {
let defNumChange = [...this.state.defNum];
defNumChange = Math.random().toString(8).substr(2);
defNumChange = parseInt(defNumChange);
console.log(defNumChange);
this.setState(() => {
return {
defNum: defNumChange,
};
});
And this is my state object also located in the context.js:
state = {
products: [],
detailProduct: detailProduct,
cart: [],
modalOpen: false,
modalProduct: detailProduct,
subTotal: 0,
delivery: 0,
totalSum: 0,
defNum: 0,
};
This is the component where i want to display my return value of the method:
import React, { Component } from "react";
import { ProductConsumer } from "../context";
export default class thankYou extends Component {
render() {
return (
<ProductConsumer>
{(value) => {
const { defNum } = value;
return (
<React-Fragement>
<div className="container">
<div className="row mt-2 mb-2">
<div className="col-md-12">
<div className="jubotron text-center text-titel">
<p></p>
<h4>Vielen Dank für deine Bestellung!</h4>
<hr />
<p className="mt-6">
Wenn dir unsere Produkte gefallen komme gerne wieder auf
uns zurück
</p>
<p className="mt-6">
<strong>
Dein .Dog.Styles. Team freut sich auf dich
</strong>
</p>
<p className="mt-6">
Bitte überprüfe deine E-Mails, um weitere Details zu
erhalten.
</p>
<hr />
<p></p>
<p className="mt-6">
<strong>Deine Bestellnummer: {defNum} </strong> <------ THIS ONE :)
</p>
</div>
</div>
</div>
</div>
</React-Fragement>
);
}}
</ProductConsumer>
);}}
Upvotes: 1
Views: 1354
Reputation: 1
Your defnum
is integer as per your state
(0) and its not iterable.It should either be an array
or Set
or object
or string to be iterable.
let defNumChange = [...this.state.defNum]; // so this won't work
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected,or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected
See doc here
What you can do is ,add double quotes
to the value (Just a hack) of defnum
to make it iterable
state = {
products: [],
detailProduct: detailProduct,
cart: [],
modalOpen: false,
modalProduct: detailProduct,
subTotal: 0,
delivery: 0,
totalSum: 0,
defNum: "0", // as string is iterable this will work
};
Upvotes: 1