Can not access value of props - javascript

I was console logging the this.props from the render function-
And in the console I can see these-
However, when I try to access any one of them, say I wanted to access the store object, then if log like this console.log(this.props.store). Like this-
Then I get this-
I have no clue what so ever I am doing wrong. If anyone knows what I am doing wrong, please let me know. Any help is appreciated!
The whole code-
import * as React from 'react';
import { connect } from 'react-redux';
import mapStateToProps from './utilities/mapStateToProp';
//tslint:disable
class App extends React.Component {
constructor(props: any){
super(props);
}
public render() {
console.log(this.props);
return (
<div className="App">
<h1>React + TypeScript = {}</h1>
</div>
);
}
}
export default connect(mapStateToProps)(App);

Save them in your component state in your constructor and access them from there.
constructo(props){
super(props)
this.state = { store: props.store }
}
And in your render()
render(){
const { store } = this.state //use the store const to access to your value
console.log(store);
}
EDITED
About not using stateless component you should declare an interface in your component in order your component understand what kind of props has the state, review this link for more information Typescript and React
interface IMyComponentProps {
someDefaultValue: string
}
interface IMyComponentState {
store: any //dont know what type is your store.
}
class App extends React.Component<IMyComponentProps, IMyComponentState> {
// ...
}
To test a workaround to check if it works try this React.Component<{},any>

Related

How can i save API response data as a variable in ReactJS so i can import it in any components?

I am following the following tutorial:
https://www.digitalocean.com/community/tutorials/react-axios-react
I am trying to import a value from an API endpoint and save it as a variable in another component.
My API endpoint is very simple compared to the example, it just responds with this:
{"USD":1168.64}
I have made a new component called PersonList.js like in the tutorial:
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`https://myendpoint.com`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<ul>
{
this.state.persons
.map(person =>
<li key={person.id}>{person.name}</li>
)
}
</ul>
)
}
}
and then in another component i have i am importing it like this:
import PersonList from './components/PersonList.js';
however i cannot console.log the variable PersonList.
I understand there is 2 issues here:
my PersonList.js is not setup to get just the USD value from the API
i dont know how to save the API response as a variable once its imported.
Can anyone help?
Since you're using class components you'll need to use the componentDidUpdate lifecycle method which will allow you to do something once the component has been updated/the state has been changed.
The previous props and state are passed as arguments to the method, and it's a good idea to use a condition to double check that things have changed so that you don't do any unnecessary work.
const { Component } = React;
class Example extends Component {
constructor() {
super();
this.state = { persons: {} };
}
// Fake API request
componentDidMount() {
const persons = { usd: 1168.64 };
this.setState({ persons });
}
// Has the state changed?
componentDidUpdate(prevProps, prevState) {
if (prevState.persons !== this.state.persons) {
console.log(this.state.persons.usd);
}
}
render() {
return (
<div>
Initial render
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

React how to access props from constructor and then make a component based on the props/state

I am not really sure how to properly ask this question but I will explain what I'm trying to do here:
So I have this parent Component which creates a Component like so:
<CurrentTemperature cityName={this.state.cityName}></CurrentTemperature>
The CurrentTemperature Component looks like this:
import React, { Component } from "react";
import "../App.css";
export default class CurrentTemperature extends Component {
constructor(props) {
super(props);
this.state = {
temperature: 0,
cityName: this.props.cityName,
};
}
componentDidMount() {
//fetch the temperature from api here
}
render() {
return (
<div>
<div className="city-temperature">
{this.state.cityName} {this.state.temperature}
</div>
</div>
);
}
}
All I'm trying to do is read the city name from the parent, then fetch the current temperature from my API, and then display both of those in the Component. But if I try to console.log(this.props.cityName) from anywhere other than from inside the city-temperature div, I always get an empty string. What is going on here?
cityName is the state of the parent component. I guess the parent component would get the "cityName" asynchronously. right? If this is the case, You have to put the temperature in the parent component as its state. And you have to insert the API call in the parent component. CurrentTemperature component will behave like a pure function component.
const CurrentTemperature = ({temperature, cityName}) => {
return (
<div className="city-temperature">
{cityName} {temperature}
</div>
);
}
I guess this is not only the solution but also the best DX.
You can remove this in your constructor, and then use this.state.cityName
constructor(props) {
super(props);
this.state = {
temperature: 0,
cityName: props.cityName,
};
}

How to pass variables from class to class

Alright, so I'm trying to simplify a project I'm working on, but of all the information I've read on the internet, none of it has answered my question. My doubt is how can I pass variables (the name of the variable, and its value) from one class to another class? Should I use props? Should I just do something similar to this.state.variable? How can it be done? I'll write a sample code just to show what I'm trying to do more visually, however, this is not my actual code. Thanks for helping :)
class FishInSea{
constructor(props){
super(props);
this.setState({fishInSea: 100});
}
render(){
return(
<div>Fish in the sea: {this.state.fishInSea}</div>
);
}
}
class FishInOcean{
constructor(props){
super(props);
this.setState({fishInOcean: <FishInSea this.props.fishInSea/> * 1000});
}
render(){
return(
<div>Fish in the ocean: {this.state.fishInOcean}</div>
);
}
}
export default FishInOcean;
You need to first make both the classes in to React components. Since both the classes modify the state so they called as statefull components. The class has to extend the Base class of React i.e., Component.
in constructor we only do state initialisations but won’t modify the state there. But you are modifying the state which isn’t correct. Instead move setState to componentDidMount.
Say suppose in FishInSea class you have fishInSea and you want to pass it to FishInOcean component as props.
Check below two corrected components how they are passed from one component to the other
import React, { Component } from “react”;
class FishInSea extends Component{
constructor(props){
super(props);
this.state = {
fishInSea: 100
}
}
componentDidMount(){
this.setState({fishInSea: 100});
}
render(){
const { fishInSea } = this.state;
return(
<div>Fish in the sea:
<FishInOcean fishInSea={fishInSea} />
</div>
);
}
}
import React, { Component } from “react”;
class FishInOcean extends Component{
constructor(props){
super(props);
this.state = {fishInOcean: 1000}
}
componentDidMount(){
this.setState({fishInOcean: 1000});
}
render(){
const { fishInOcean} = this.state;
const { fishInSea } = this.props;
return(
<div>Fish in the ocean: {fishInOcean}
{fishInSea}
</div>
);
}
}
export default FishInOcean;
/*There was a typo*/

Javascript ES6 (React) How to use a method of an imported class?

Using javascript ES6 (React), I'm not able to call a simple method of an imported class.
What's wrong with this code?
TypeError: WEBPACK_IMPORTED_MODULE_1__Seed.a.test is not a
function
// App.js
import React from 'react';
import Seed from './Seed';
class App extends React.Component {
constructor(props) {
super(props);
console.log('start1');
Seed.test();
}
render() {
return("ei");
}
}
export default App;
and
// Seed.js
import React from 'react';
class Seed extends React.Component {
constructor(props) {
super(props);
console.log('seed1');
}
test() {
console.log('seed test');
}
};
export default Seed;
There are few options, depending on what you're trying to do
1) If this function is unrelated to an instance of a Seed, then make it static.
class Seed extends React.Component {
static test() {
console.log('seed test');
}
// ...etc
}
Then you can call it the way you're already calling it.
2) If it needs to be tied to a specific instance of a seed, you could new one up and then call it. For example:
const mySeed = new Seed();
mySeed.test();
Given that Seed is a react component this is very likely not what you want to do, since you should let react do the instantiating of components and then interact with it through props
3) Use refs to let react give you a reference to the component. I'll assume you're using react 16 or higher and thus have access to React.createRef
constructor(props) {
super(props);
this.seedRef = React.createRef();
}
componentDidMount() {
this.seedRef.current.test();
}
render() {
return <Seed ref={this.seedRef}/>
}
This is better, but its still questionable that you would want to interact with a component this directly.
4) Use props, don't call it directly. Exactly how to do this depends what you're trying to do, but suppose you want to only call the method if some condition is true. Then you could pass a prop in to the Seed, and the seed calls the method itself.
// in App:
render() {
render <Seed shouldDoStuff={true} />
}
// In seed:
constructor(props) {
super(props);
if (props.shouldDoStuff) {
this.test();
}
}
You can do that with declare test as static like this
class Seed extends React.Component {
static test() {
console.log('seed test');
}
constructor(props) {
super(props);
console.log('seed1');
}
};
if you want call test in Seed component use Seed.test()
You cannot access a class' method like that since it's not static.
You would need to have App render with a <Seed /> and get a ref to that component.
// App.js
import React from 'react';
import Seed from './Seed';
class App extends React.Component {
constructor(props) {
super(props);
console.log('start1');
this.seedRef = React.createRef();
}
componentDidMount() {
// seedRef is the Seed instance
this.seedRef.current.test();
}
render() {
return(<Seed ref={this.seedRef} />);
}
}
export default App;

Transferring State Between Components - React

If I have a state in the App class, and I want to transfer those values into SecondApp, how do you go about that? I've tried using props but when I console log it, I get undefined.
Excuse the nooby question, I'm fairly new and trying to get my hands dirty, haha.
class App extends Component {
constructor(props) {
super(props)
this.state = {
todo: ['hello', 'hey']
}
}
}
class SecondApp extends Component {
render() {
return (
<p>?</p>
)
}
}
If you are passing the props correctly, they shouldn't turn up undefined. Props would be the correct way to go about this though!
class App extends Component {
constructor(props) {
super(props)
this.state = {
todo: ['hello', 'hey']
}
}
render() {
return <SecondApp testProp={this.state.todo}/>;
}
}
class SecondApp extends Component {
render() {
return <div>this is the prop: {this.props.testProp}</div>;
}
}
If you pass it through like that, you'll see the prop show up as "hellohey", check out the JSFiddle. Next off you'll likely want to render these items in a list, and will need to handle that accordingly. This article will point you in the right direction!
First you need to call SecondApp in App and then pass props.
class SecondApp extends React.Component {
render() {
return ( <
p > {this.props.todo} < /p>
)
}
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
todo: ['hello', 'hey']
}
}
render() {
return ( <
SecondApp todo = {
this.state.todo
} />
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
If you mean to pass data from one app to another (that means, you render an app on an id and another app on another id) you can use events.
Whenever the state of the first app updates, you can dispatch an event and put an event listener on the other app, that updates it's state.
This is a common way to share data between independent modules/apps.
You can read more about this when you google "observer subscriber pattern".
Otherwise, if you mean to pass data to a child component, you really should read the react documentation.

Categories