Is it possible to access other state values in same constructor? - javascript

Is it possible to access a state value in constructor, and use it in a different state value in same constructor? See example below.
class App extends Component {
constructor(props){
super(props);
this.state = {
values1: {
value1: "value 1"
},
values2: {
value2: "value 2"
},
selected: {
selectedValue: `Selected value is: ${this.state.values1.value1}`
}
}
}
}

It will not work.
But you can set another variable's value in componentDidMount.
See my example :
class App extends Component {
constructor(props){
super(props);
this.state = {
values1: {
value1: "value 1"
},
values2: {
value2: "value 2"
},
}
}
componentDidMount(){
this.setState({selectedValue: "Selected value is: "+ this.state.values1.value1});
}
render() {
return (
<div>
<p>
{this.state.selectedValue}
</p>
</div>
)
}
}
Here is a working example - https://stackblitz.com/edit/react-2ra5ht

Yes it is but you would have to use the setState() method to do so
You would declare the selected state above then within the constructor you could then usethis.setState({selected: this.state.values1.value1}) to set the state.

Yes, you approach will work with small modification. state is plain JavaScript object, so you may assign new properties to it several times in constructor.
constructor () {
super ();
this.state = {
values1: {
value1: "value 1"
},
values2: {
value2: "value 2"
}
}
this.state.selected = {
selectedValue: "Selected value is: " + this.state.values1.value1
}
}
And sample

Related

React-Select if value exists show value if not show placeholder text

I'm using this component here: https://react-select.com/home
What I'm trying to accomplish is on page load if my array contains a value in my Assigned element then I want to display that by default in my react-select box if not then I want my placeholder Assign to to show.
Here is how my select looks:
<Select
value={this.state.Product[0].Assigned ? this.state.Product[0].Assigned : selectedAssigned}
onChange={this.handleChangeAssigned}
options={this.state.AssignedList}
placeholder={<div>Assign to:</div>}
/>
In my Product[0].Assigned there is currently a value, however the dropdown still has the placeholder Assign To. I tried changing value to value={this.state.Product[0].Assigned} but still no luck.
Here is my change handle:
handleChangeAssigned = selectedAssigned => {
this.setState(
{ selectedAssigned },
() => console.log(`Option selected:`, this.state.selectedAssigned)
);
};
It seems like you are storing the same data in multiple places. You are checking if you have an assignment by looking at this.state.Product[0].Assigned. But when you select an assignment you are not updating that property. Instead you are updating a completely separate property this.state.selectedAssigned. this.state.Product[0].Assigned never changes so if you see a placeholder at first then you will always see a placeholder.
The value that you set on the Select needs to be the same as the value that you update.
import React from "react";
import Select from "react-select";
interface Option {
label: string;
value: string;
}
interface State {
Product: any[];
AssignedList: Option[];
selectedAssigned: Option | null;
}
export default class MyComponent extends React.Component<{}, State> {
state: State = {
Product: [],
AssignedList: [
{ label: "a", value: "a" },
{ label: "b", value: "b" },
{ label: "c", value: "c" }
],
selectedAssigned: null
};
handleChangeAssigned = (selectedAssigned: Option | null) => {
this.setState({ selectedAssigned }, () =>
console.log(`Option selected:`, this.state.selectedAssigned)
);
};
render() {
return (
<Select
value={this.state.selectedAssigned}
onChange={this.handleChangeAssigned}
options={this.state.AssignedList}
placeholder={<div>Assign to:</div>}
/>
);
}
}
Code Sandbox Link

React/JSX: Can I use a state variable in another state variable?

I have something like this, where I would like to create array in the state from a variable initialized directly above it. I get the error cards is not defined. Is there a way around this? I need to set this array specifically in the state.
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: [
{
name: "Name 1",
description: "dfdsfaf",
},
{
name: "Name 2",
description: "dsfsfasf",
},
{
name: "Name 3",
description: "daslkdjadlajsd",
},
],
names: cards.map(item => item.name)
};
}
...
}
You can do this in javascript as follows:
const cards = [...]
const names = = cards.map(...)
this.state = { cards: cards, names: names }
You should probably not do this though and set state to only the cards and move the call to calculate the names to your render method

TypeError: variable is undefined despite being able to log the variable correctly

I'm trying to get a simple list of lessons contained in a course from an endpoint.
If I try console.log(this.state.course.lessons) an array contained 3 items is displayed.
However,if I try console.log(this.state.course.lessons.map(//function) I keep getting
TypeError: this.state.course.lessons is undefined
How can I map a function to the lessons array so I can render them as a list.
component
import React, { Component } from 'react'
export class CourseDetail extends Component {
constructor(props) {
super(props);
this.state = {
course: []
};
}
componentDidMount() {
fetch(`http://127.0.0.1:8000/api/courses/${this.props.match.params.id}`)
.then(res => res.json())
.then((course) => {
this.setState({
course: course,
});
console.log(this.state.course.lessons)
});
}
render() {
return (
<div>
{this.state.course.lessons.map((lesson)=>(console.log(lesson)))}
<h1>{this.state.course.title}</h1>
</div>
)
}
}
export default CourseDetail
json returned from end point
{
"id": 1,
"lessons": [
1,
2,
3
],
"owner": 1,
"rating": 0,
"title": "Course 1",
"description": "course 1 desc",
"pub_date": "2019-11-23",
"is_live": false,
"category": 1
}
Most obvious solution would be just to give the object a default state if you want to access it:
constructor(props) {
super(props);
this.state = {
course: {
lessons: []
}
};
}
The problem on your code is the life cycles (Mount-> Render-> DidMount), and in this render, u have not fetch the data yet.
You can try this:
render() {
if (!this.state.course.lessons) return null //this line
return (
<div>
{this.state.course.lessons.map((lesson)=>(console.log(lesson)))}
<h1>{this.state.course.title}</h1>
</div>
)
}

Put image as an object into state variable and pass it as a props

I was trying to put an image as an object into state and pass the state as a props in react but it's not passing anything.
import xaprikaScreen from "./images/xaprikaScreenShot.jpg";
import linguadenScreen from "./images/linguadenScreenShot.jpg";
export class Portfolio extends Component {
constructor() {
super();
this.state = {
currentProject: 0,
projects: [
{
id: 1,
projectName: "Linguaden.com",
projectLink: "www.linguaden.com",
githubLink: "",
displayPicture: { linguadenScreen },
projectDescription: ""
},
{
id: 2,
projectName: "Xaprika.com",
projectLink: "www.Xaprika.com",
githubLink: "",
displayPicture: { xaprikaScreen },
projectDescription: ""
}
]
};
}
render() {
return (
<Projects imageSource={this.state.projects[this.state.currentProject["displayPicture"]}/>
);
}
}
}
Here i have imported 2 images as an object, then i have assigned them into state and then i am trying to pass those variables as props.
The problem here is that you're doing this.state.currentProject["displayPicture"]. The value of currentProject is 0, and 0.displayPicture is undefined. You're then doing this.state.projects[this.state.currentProject["displayPicture"], which not only doesn't have a closing bracket, even if it did that would be equivalent to this.state.projects[undefined] which is also undefined.
Replace your render function with the below code and it should work.
render() {
return (
<Projects imageSource={this.state.projects[this.state.currentProject].displayPicture} />
);
}

react. Can't pass object into component

In one render function I create 1-3 components BigText
return (<div>{ d.sql[0] !== null ? <BigText content={d.sql[0]}>SQL</BigText> : <span> </span> }
{ d.event[0] !== null ? <BigText content={d.event[0]}>Event</BigText> : <span> </span>}
{ d.stacktrace[0] !== null ? <BigText content={d.stacktrace[0]}>Trace</BigText> : <span> </span>}</div>)
d is a real object Object {sql: Array[1], stacktrace: Array[1], event: Array[1]}. This code seems correct.
But the object passed as content is not present in the BigText component render.
class BigText extends React.Component {
constructor(props) {
super(props);
this.toggleViewer = this.toggleViewer.bind(this);
console.log(this);
}
toggleViewer() {
console.log(this);
this.props.viewerToggle(this.props.content);
}
render() {
console.log(this);
return (<FlatButton primary={true} onTouchTap={this.toggleViewer}>{this.props.children}</FlatButton>)
}
}
BigText.propTypes = {
class: React.PropTypes.string,
content: React.PropTypes.any.isRequered
}
Logged this object. As you see below props.content is null when component has been called to render, it is also null when constructor has been called:
BigText
props
children: "SQL"
content: null
isViewerOpened: false
viewerToggle: function ()
__proto__: Object
context: Object
refs: Object
updater: Object
...
Where to dig to solve this issue?

Categories

Resources