I am using react native and react navigation for routing.
How to update state from another component/page?
HomeScreen
export class HomeScreen extends Component {
constructor(){
this.state = {
test: ''
}
}
updateState = ()=>{
this.setState({test:'new value'});
}
}
SideMenuScreen
import { HomeScreen } from "./home";
export class SideMenuScreen extends Component {
updateHomeState = ()=>{
let oHome = new HomeScreen();
oHome.updateState();
}
}
My App.js and routing and sidemenu config as below :
import { createAppContainer, createDrawerNavigator } from "react-navigation";
import { SideMenuScreen } from "./screens/Sidemenu";
import { HomeScreen } from "./screens/Home";
export default class App extends Component {
render() {
return(
<AppContainer></AppContainer>
);
}
}
const AppNavigator = createDrawerNavigator(
{Home: HomeScreen,
other: otherpage},
{
contentComponent: SideMenuScreen
}
);
const AppContainer = createAppContainer(AppNavigator);
updateState executing but not updating state.
If you have to update from the child component
You will have to pass down the Handlers from the component which holds the state to update the values, child component can make use of these handlers to update the state
If you have to update from some other location
You will have to do a level up the State and follow the same has above.
LevelUpComponent
export class App extends Component {
constructor(){
this.state = {
test: ''
}
}
updateState = (values)=>{
this.setState(values);
}
render(){
return <div>
<HomeScreen></HomeScreen>
<SideMenuScreen updateState={this.updateState}></SideMenuScreen>
</div>
}
}
Since you're not haveing Parent-Child relationship between your components ... thi s could be accomplished through Redux Action
HomeScreen;
export class HomeScreen extends Component {
constructor() {
this.state = {
test: ""
};
}
componentWillReceiveProps(nextProps) {
const { test: nextTest } = nextProps;
const { test } = this.props;
if (nextTest !== test) {
this.setState({ test: nextTest });
}
}
}
const mapStateToProps = ({ yourReducerName: test }) => ({ test });
export connect(mapStateToProps)(HomeScreen);
import { HomeScreen } from "./home";
import { connect } from "tls";
class SideMenuScreen extends Component {
updateHomeState = () => {
const { updateHomeStateAction } = this.props;
updateHomeStateAction({ test: 'New Value' });
};
}
export default connect(null, { updateHomeStateAction })(SideMenuScreen);
when you navigate to next screen pass this function in params,
this.props.navigate("SideMenuScreen",{update:this.updateState});
And in your side menu screen,
call it using props,
this.props.navigation.state.params.update();//you can pass params also if needed
You can do this by using ref.
HomeScreen
export class HomeScreen extends Component {
constructor(){
this.state = {
test: ''
}
}
updateState = ()=>{
this.setState({test:'new value'});
}
}
SideMenuScreen
import { HomeScreen } from "./home";
export class SideMenuScreen extends Component {
updateHomeState = ()=>{
this.homeScreen.updateState();
}
render(){
return(
<HomeScreen ref={(ele) => this.homeScreen = ele}/>
);
}
}
Related
Login.js in functional component
import React, { useState } from 'react';
import { connect } from 'react-redux';
import { login } from '../actions/auth';
const Login = ({ login, isAuthenticated }) => {
return (
<div>
// some code here
</div>
);
};
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps, { login })(Login);
How can I use above mapStateToProps function in class component as I used above in functional component?
Login.js in class component
import React, {Component} from "react";
class Login extends Component{
constructor(props) {
super(props);
this.state = {
search:'',
}
}
render() {
return(
<div>
//some code here
</div>
)
}
}
export default Login;
In class components mapStateToProps works the same as functional components, I feel there are only differences in some syntax or calling approaches.
It does not matter if a mapStateToProps function is written using the function keyword (function mapState(state) { } ) or as an arrow function
(const mapState = (state) => { } ) - it will work the same either way.
Class component with mapStateToProps
import React, {Component} from "react";
import { connect } from 'react-redux';
import { login } from '../actions/auth';
class Login extends Component{
constructor(props) {
super(props);
this.state = {
search:'',
}
}
render() {
const { isAuthenticated } = this.props;
return(
<div>
//some code here
</div>
)
}
}
function mapStateToProps(state) {
const { isAuthenticated } = state.auth.isAuthenticated
return { isAuthenticated }
}
export default connect(mapStateToProps)(Login)
As you can see there is only 1 major difference is: In Class component we are reading the value isAuthenticated from this.props whereas in the Functional component we are getting the value as arguments.
For information read more about mapStateToProps. https://react-redux.js.org/using-react-redux/connect-mapstate
I would like to use some data I received from firestore to build a quiz. Unfortunately I can console.log the array, but if I use .length it is undefined.
Is this problem caused by some lifecycle or asnynchronous issue?
Thanks in advance!
import React, { Component } from 'react';
import { connect } from 'react-redux';
class LernenContainer extends Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
render() {
return (
<div className="lernenContainer">
LernenContainer
{
console.log(this.props.firestoreData),
// prints array correctly
console.log(this.props.firestoreData.length)
// is undefined
}
</div>
);
}
}
const mapStateToProps = state => {
return {
firestoreData: state.firestoreData
};
};
const mapDispatchToProps = dispatch => {
return {
// todo Achievements
};
};
export default connect(mapStateToProps, mapDispatchToProps) (LernenContainer);
console.log(this.props.firestoreData):
Try below code
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types'
class LernenContainer extends Component {
constructor(props) {
super(props);
}
static propTypes = {
firestoreData: PropTypes.object.isRequired
}
render() {
const { firestoreData } = this.props
console.log(firestoreData);
console.log(firestoreData.length);
return (
<div className="lernenContainer">
</div>
);
}
}
const mapStateToProps = (state) => ({
firestoreData: state.firestoreData
})
const mapDispatchToProps = (dispatch) => ({
})
export default connect(mapStateToProps,mapDispatchToProps)(LernenContainer);
I'm building a Todo app using react+redux. When I add new todo in my list, state of store and state of TodoList component are updated successfully but My todoList code not working properly. React component is not rendering list.
Structure of state is below.
State = [
{
id,
text,
completed
},...
]
My code is below.
Todo.js
import React, { Component } from 'react';
import Form from './Form';
import TodoList from './TodoList';
import Filter from './Filter';
class ToDo extends Component {
render() {
return (
<div>
<h2>Todo App</h2>
<Form />
<TodoList />
<Filter />
</div>
);
}
}
export default ToDo;
TodoList.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { toggleToDo } from '../actions';
class TodoList extends Component {
constructor (props){
super(props);
this.state = {
list: []
};
}
render() {
console.log(this);
const todolist = this.state.list;
return (
<ul>
{
todolist.map(function(listValue) {
return <li>{listValue.text}</li>;
})
}
</ul>
);
}
}
const mapStateToProps = (state) => {
console.log('TodoList state',state);
return {
todos: state
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({toggleToDo},dispatch);
}
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);
You are mapping your state to props with mapStateToProps so you should get this state value from your props.
const { todos } = this.props; and iterate on todos instead of todolist.
I'm trying to lazy load routes in React by implementing the AsyncCompoment class as documented here Code Splitting in Create React App. Below is the es6 asyncComponent function from the tutorial:
import React, { Component } from "react";
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
I've written this function in typescript and can confirm that components are indeed being loaded lazily. The issue I face is that they are not being rendered. I was able to determine that the component object is always undefined in the componentDidMount hook:
//AsyncComponent.tsx
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
The object being returned from the importComponent function has the following properties:
{
MyComponent: class MyComponent: f,
__esModule: true
}
I modified the componentDidMount method to take the first property of this object, which is the MyComponent class. After this change my project is now lazy loading the components and rendering them properly.
async componentDidMount() {
const component = await importComponent();
this.setState({
component: component[Object.keys(component)[0]]
});
}
My best guess is that I have not written this line properly in typescript:
const { default: component } = await importComponent();
I'm calling the asyncComponent method like so:
const MyComponent = asyncComponent(()=>import(./components/MyComponent));
Anyone know how to implement the AsyncComponent in typescript? I'm not sure if simply getting the 0 index on the esModule object is the correct way to do it.
// AsyncComponent.tsx
import * as React from "react";
interface AsyncComponentState {
Component: null | JSX.Element;
};
interface IAsyncComponent {
(importComponent: () => Promise<{ default: React.ComponentType<any> }>): React.ComponentClass;
}
const asyncComponent: IAsyncComponent = (importComponent) => {
class AsyncFunc extends React.PureComponent<any, AsyncComponentState> {
mounted: boolean = false;
constructor(props: any) {
super(props);
this.state = {
Component: null
};
}
componentWillUnmount() {
this.mounted = false;
}
async componentDidMount() {
this.mounted = true;
const { default: Component } = await importComponent();
if (this.mounted) {
this.setState({
component: <Component {...this.props} />
});
}
}
render() {
const Component = this.state.Component;
return Component ? Component : <div>....Loading</div>
}
}
return AsyncFunc;
}
export default asyncComponent;
// Counter.tsx
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
interface CounterState {
currentCount: number;
}
class Counter extends React.Component<RouteComponentProps<{}>, CounterState> {
constructor() {
super();
this.state = { currentCount: 0 };
}
public render() {
return <div>
<h1>Counter</h1>
<p>This is a simple example of a React component.</p>
<p>Current count: <strong>{this.state.currentCount}</strong></p>
<button onClick={() => { this.incrementCounter() }}>Increment</button>
</div>;
}
incrementCounter() {
this.setState({
currentCount: this.state.currentCount + 1
});
}
}
export default Counter;
//routes.tsx
import * as React from 'react';
import { Route } from 'react-router-dom';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import asyncComponent from './components/AsyncComponent';
const AsyncCounter = asyncComponent(() => import('./components/Counter'));
export const routes = <Layout>
<Route exact path='/' component={Home} />
<Route path='/counter' component={AsyncCounter} />
</Layout>;
I'm trying to fetch records from backend graphql service and render them with Array.map function. Unfortunately before they're loaded I get error because they are undefined. I tried to set default props on component but it didin't work. Do i have to check if everything is loaded or is there specific way to inject default values into those props. My code looks like that right now
import React from 'react';
import { graphql } from 'react-apollo';
import { fetchTasks } from '../../../graphql/tasks';
import { Dashboard } from '../components/Dashboard';
const propTypes = {
data: React.PropTypes.shape({
tasks: React.PropTypes.array
})
};
const defaultProps = {
data: {
tasks: []
}
};
class DashboardContainer extends React.Component {
render() {
const titles = this.props.data.tasks.map(task => task.title);
return(
<Dashboard
titles={titles}
/>
);
}
}
DashboardContainer.propTypes = propTypes;
DashboardContainer.defaultProps = defaultProps;
export default graphql(fetchTasks)(DashboardContainer);
Yes you have to check if the query has finished to load. You could go through this nice tutorial, where you build a pokemon app. The link points to the part where they show a basic query and how you check if it is loaded.
In your case it could look like this:
import React from 'react';
import { graphql } from 'react-apollo';
import { fetchTasks } from '../../../graphql/tasks';
import { Dashboard } from '../components/Dashboard';
const propTypes = {
data: React.PropTypes.shape({
tasks: React.PropTypes.array
})
};
const defaultProps = {
data: {
tasks: []
}
};
class DashboardContainer extends React.Component {
render() {
if (this.props.data.loading) {
return <div > Loading < /div>;
}
const titles = this.props.data.tasks.map(task => task.title);
return ( <
Dashboard titles = {
titles
}
/>
);
}
}
DashboardContainer.propTypes = propTypes;
DashboardContainer.defaultProps = defaultProps;
export default graphql(fetchTasks)(DashboardContainer);