componentDidMount() not working in reactJs v15.x - reactjs

I'm trying to use componentDidMount to set data from axios to component state but it doesn't work
I checked it by this simple code
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from 'axios';
import "./styles.css";
class App extends Component {
constructor(props){
super(props);
state:{
textures:null
}
componentDidMount(){
let data = axios.get('http://127.0.0.0:8000/wall)
.then(res => {
this.setState({textures:res}
});
)
}
render() {
return (this.state.textures);
}
}
export default new App();
in index.js
import App from '/app.js';
console.log(App.render());
the output is null

Move your state object to the class property from the constructor.
Your constructor has its local state variable which has nothing to do with component state.
You have to either set the property from the constructor or intialize from the class.
class App extends Component {
state = {
textures: null
}
............

Related

How to include the Match object into a Reacts component class?

I am using react router v5, and trying to get URL parameters by props match object into my react component class. However it is not working! What am I doing wrong here?
When I create my component as a JavaScript function it all works fine, but when I try to create my component as a JavaScript class it doesn't work.
Perhaps I am doing something wrong? How do I pass the Match object in to my class component and then use that to set my component's state?
here code:
import React, { Component } from 'react';
import { Link} from "react-router-dom";
export class JobDetail extends Component {
state = {
// jobsData: [],
}
async componentDidMount() {
const props = this.props.match;
console.log("---props data---",props); // it's showing undefined
}
render() {
return (
<>
test message
</>
)
}
}
export default JobDetail

what is best way to get props in React / React Native

I'm really regarding props in React/React-Native. I have a parent view. In this view I'm getting the user data from a LocalStorage.['
import React, { Component } from 'react';
import { Container, Content, View } from 'native-base';
import NutrionalToolbar from '../../components/NutrionalToolbar';
import { AsyncStorage } from 'react-native';
export default class LogsScreen extends Component {
state = {
user: '',
}
componentWillMount() {
this._bootstrapAsync();
}
_bootstrapAsync = async () => {
const user = await AsyncStorage.getItem('user');
this.setState({ user: JSON.parse(user) })
};
render() {
return (
<Container>
<NutrionalToolbar user={this.state.user} />
</Container>
);
}
}
Now inside the NutrionalToolbar component I have this.
import React, { Component } from 'react';
import { View } from 'native-base';
class NutrionalToolbar extends Component {
constructor(props) {
super(props)
console.log(this.props) // This renders an empty user object
}
render() {
console.log(this.props) // This renders the user object with values
return (
<View>
</View>
);
}
}
export default NutrionalToolbar;
How can I get this.props values inside the constructor. I'm getting the values inside render method. Why isn't working inside the constructor?
I would recommend looking into the componentDidUpdate lifecycle hook because, even if you could access the initial user prop in the constructor, you wouldn't be able to access updates to that prop in the constructor.
import React, { Component } from 'react';
import { View } from 'native-base';
class NutrionalToolbar extends Component {
componentDidUpdate() {
console.log(this.props) // This will always log the current props
}
render() {
return (<View></View>);
}
}
export default NutrionalToolbar;

Context data does not get passed into nested component: React+Typescript+ContextAPI

I am using context API to avoid prop drilling across the components. I have a component which has two popup modal's(components). When I am trying to fetch the context data within Enclosing component data, but within the modal I would not get. If I pass again pass this context data as a props to these modal's and then if I fetch this props accessor then I am able to fetch. Where am I going wrong? If I am not wrong, this context API does not depend on the nested levels, can someone help me here?
CacheContext.tsx
import React from "react";
const context = React.createContext(null);
export default context;
ContextProvider.tsx
import React, {Component} from "react";
import context from './CacheContext';
var TinyCache = require( 'tinycache' );
var cache = new TinyCache();
class ContextProvider extends Component {
render() {
return (
<context.Provider value={cache}>
{this.props.children}
</context.Provider>
);
}
}
export default ContextProvider;
ComponentA.tsx
import * as React from "react";
import context from "../Utilities/CacheContext";
export default class ComponentA extends React.Component<{}, {}> {
componentDidMount() {
console.log(this.context) // I am able to the data here
}
render(){
return(
<Modal1/> //if I pass this as context={this.context} then it works
<Modal2/>
)
}
}
ComponentA.contextType=context;
Modal1.tsx
import * as React from "react";
import context from "../Utilities/CacheContext";
export default class Modal1 extends React.Component<{}, {}> {
componentDidMount() {
console.log(this.context) // I am unable able to the data here , If I use this.props.context and pass the context as props then I am able to get
}
render(){
return(
//some content
)
}
}
Modal1.contextType=context;
In the new context API ( https://reactjs.org/docs/context.html#api ) You should use the context.Consumer component using a function as children:
<context.Consumer>
{cache => console.log(cache)}
</context.Consumer>
If you need the cache in componentDidMount, pass the cache to a sub-component like this:
// render:
<context.Consumer>
{cache => <SubComponent cache={cache}/>}
</context.Consumer>
// SubComponent:
class SubComponent {
componentDidMount() {
console.log(this.props.cache);
}
}

How to access state of one component into another component in react

import React, { Component } from 'react';
class one extends React.Component
{
constructor()
{
super();
this.state = {
number:26
}
}
render()
{
return(
<div></div>
);
}
}
export default one;
import React, { Component } from 'react';
import one from './one'
class HomePage extends React.Component
{
render()
{
return(
<div>{one.state.number}</div>
);
}
}
export default HomePage;
is it possible to access number state
is there any way to access state of one component into another component?
please suggest me if any solution is present.
As Shubam has explained it, Though I would like to form it as a complete answer
First of all, I would like to let you know that Never Use lowercase letters to name your React Components.So name your component to One instead of one.
Now Comming back to your question:-
No This is not Possible, If your app contains few components then it's better to pass the state object as the props, But if your app contains too many components then better to use predictable state containers like Redux or Flux rather than passing state as props.
So you may apply these changes and I hope You will get What You Desire:-
One Component:-
import React, { Component } from 'react';
import Homepage from './homepage';
class One extends React.Component
{
constructor()
{
super();
this.state = {
number:26
}
}
render()
{
return(
<Homepage data={this.state}/>
);
}
}
export default One;
Homepage Component:-
import React, { Component } from 'react';
class Homepage extends React.Component
{
render()
{
console.log("this is homepage",this.props);
return(
<div>{this.props.data.number}</div>
);
}
}
export default Homepage;
Please Raise Your doubts if any, Or if you find any error in it.

Meteor React Komposer: Execute Component Constructor AFTER ready subscription

I have a React Component Post:
export class Post extends React.Component {
constructor(props) {
this.state = this.props;
}
...
}
, which I compose with
import { composeWithTracker } from 'react-komposer';
import { composeWithTracker } from 'react-komposer';
import Post from '../components/post.jsx';
function composer(props, onData) {
const subscription = Meteor.subscribe('post', props.postId);
if (subscription.ready()) {
const data = {
ready: true,
posts: Posts.findOne(props.postId).fetch()
}
onData(null, data);
} else {
onData(null, {ready: false});
}
}
export default composeWithTracker(composer)(Post);
. As given in the Post Component I want to put some properties in the state of the component, but the constructor will be executed before I get the data from the composer!
How do I wait until the data is send and then put my props into the state?
Isn't this what the React Kompose should do? BTW I am using Version 1.~ to get composeWithTracker.
You could use componentWillReceiveProps to get new properties and set as component state. This function will run whenever there are new properties passed to component:
export class Post extends React.Component {
// ...
componentWillReceiveProps(nextProps) {
this.setState({
...nextProps,
});
}
// ...
}

Resources