`App` - not retrieves the store static value - reactjs

my app component, not retrieves the store default value at all. any one help me?
here in my index.js file:
import React from "react";
import ReactDOM from "react-dom";
import { Provider, connect } from "react-redux";
import store from "./Store";
import "./styles.css";
function App(props) {
console.log("propps", props);
return (
<div className="App">
<h1>Hello CodeSandbox{props.count}</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const getState = state => {
console.log(state); //getting empty object instead `count`
return state;
};
connect(
getState,
null
)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
Live Demo

const ConnectedApp = connect(
getState,
null
)(App);
then render ConnectedApp not App

Related

useWeb3React hook doesn't return provider

I want to access the Ethereum blockchain through Cloudflare Ethereum Gateway. I am trying to use web3-react library, but useWeb3React doesn't return object with provider property.
codesandbox.io
index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import Web3 from "web3";
import { Web3ReactProvider } from "#web3-react/core";
import App from "./App";
function getLibrary(provider) {
const web3Provider = new Web3.providers.HttpProvider(
"https://cloudflare-eth.com"
);
const web3 = new Web3(web3Provider);
return web3;
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Web3ReactProvider getLibrary={getLibrary}>
<App />
</Web3ReactProvider>
</StrictMode>,
rootElement
);
App.js
import { useWeb3React } from "#web3-react/core";
import "./styles.css";
export default function App() {
const web3React = useWeb3React();
console.log({ web3React });
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
There is an issue in the library describing this exact problem with the solution here: https://github.com/NoahZinsmeister/web3-react/issues/126#issuecomment-783057749
Seems like you have to call web3React.activate() in your App.js with whatever connector you want to use. So for example with the #web3-react/injected-connector:
import { useWeb3React } from "#web3-react/core";
import { InjectedConnector } from "#web3-react/injected-connector";
import "./styles.css";
export default function App() {
const web3React = useWeb3React();
web3React.activate(new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
}));
console.log({ web3React });
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

Why is the value not shown in react context?

Not sure why react context is not using the value passed in provider?
import { createContext } from "react";
const initialState = {
isOpen: false
};
export const alertContext = createContext(initialState);
export default (props) => {
return (
<>
<alertContext.Provider value={{ isOpen: true }}>
{props.children}
</alertContext.Provider>
</>
);
};
import "./styles.css";
import { useContext } from "react";
import AlertProvider, { alertContext } from "./AlertProvider";
export default function App() {
let value = useContext(alertContext);
return (
<div className="App">
<AlertProvider>
<pre>{JSON.stringify(value)}</pre>
</AlertProvider>
</div>
);
}
Why is the value for isOpen not true?
https://codesandbox.io/s/serene-faraday-1oib3?fontsize=14&hidenavigation=1&theme=dark
You need to wrap your provider around App in index.js
as shown:
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import AlertProvider from "./AlertProvider";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<AlertProvider>
<App />
</AlertProvider>
</StrictMode>,
rootElement
);
and your app.js will look like this:
import "./styles.css";
import { useContext } from "react";
import { alertContext } from "./AlertProvider";
export default function App() {
let value = useContext(alertContext);
return (
<div className="App">
<pre>{JSON.stringify(value)}</pre>
</div>
);
}

How to get access to any context in app.js, out of the render function

I am trying to get the login status in my ContextProvider in app.js which is the root of my application so it is not possible to get it with useContext. At least I could not manage to get it. I am planning to render different AppStack navigator stack based on the loginStatus, so I need to get the state in app.js. Do you know any way to work around this problem?
This is my app.js file:
const App = props => {
const [isLoading, setIsLoading] = useState(true);
const _cacheResourcesAsync = async () => {
await Font.loadAsync({
"poppins-regular": require("./assets/fonts/Poppins-Regular.ttf"),
"poppins-medium": require("./assets/fonts/Poppins-Medium.ttf"),
"poppins-bold": require("./assets/fonts/Poppins-Bold.ttf"),
"segoe-ui": require("./assets/fonts/segoe-ui.ttf"),
"Montserrat-Regular": require("./assets/fonts/Montserrat-Regular.ttf"),
Dosis: require("./assets/fonts/Dosis.ttf"),
"FjallaOne-Regular": require("./assets/fonts/FjallaOne-Regular.ttf"),
"Lobster-Regular": require("./assets/fonts/Lobster-Regular.ttf")
});
};
if (isLoading) {
return (
<AppLoading
startAsync={_cacheResourcesAsync}
onFinish={() => setIsLoading(false)}
onError={console.warn}
/>
);
} else {
return (
<ExperienceProvider>
<AppProvider>
<AppStack
loginStatus={loginStatus}
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
</AppProvider>
</ExperienceProvider>
);
}
};
export default App;
Wrapping the element in Provider can help .
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./styles/index.scss";
import * as serviceWorker from "./serviceWorker";
import { LoginProvider } from "./context/loginContext.js";
ReactDOM.render(
<React.StrictMode>
<LoginProvider>
<App />
</LoginProvider>
</React.StrictMode>,
document.getElementById("root")
);
serviceWorker.unregister();

How to create multiple instance with `redux` based component?

I am using Redux with my reactjs app. I strucking with 2 doubts here.
I would like to create multiple instace of redux based component
I like to control / show the store data to other component too..
how to achieve the both? any one help me?
I tried like this: got error:
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider } from "react-redux";
import reducer from "./reducer";
import App from "./App";
import Source from "./Source"; //how to get store data here too..
import "./styles.css";
var store = createStore(reducer);
const rootElement = document.getElementById("container");
ReactDOM.render(
<Provider store={store}>
<App />
<App /> //throws error
</Provider>,
rootElement
);
Live Demo
The Provider tag should contain a single React child element. You can overcome this by creating a fake Higher-Order-Component as below:
const Aux = props => props.children;
Please try the below code:
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider } from "react-redux";
import reducer from "./reducer";
import App from "./App";
import Source from "./Source";
import "./styles.css";
var store = createStore(reducer);
const Aux = props => props.children;
const rootElement = document.getElementById("container");
ReactDOM.render(
<Provider store={store}>
<Aux>
<App />
<App />
</Aux>
</Provider>,
rootElement
);
You must connect your component at Redux Store like this:
import React, { Component } from "react";
import { connect } from "react-redux";
class Source extends Component {
render() {
const { counter, increaseCount, decreaseCount } = this.props;
return (
<div className="container">
<h1>How to show count here?</h1>
<h2>{counter}</h2>
<button
onClick={() => {
increaseCount();
}}
>
How to increase count?
</button>
</div>
);
}
}
const mapStateToProps = state => ({
counter: state.count
});
var increaseAction = { type: "increase" };
var decreaseAction = { type: "decrease" };
const mapDispatchToProps = dispatch => {
return {
increaseCount: function() {
return dispatch(increaseAction);
},
decreaseCount: function() {
return dispatch(decreaseAction);
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Source);

React Router not rendering component initially

This is weird one for me. I start my app up locally. I just have a Header and TaskPage in my App like so.
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import Header from '../components/header';
import TasksPage from '../pages/tasks';
import { Route } from 'react-router';
class App extends Component {
render() {
return (
<div>
<Header />
<main>
<Route exact path="/" component={TasksPage} />
</main>
</div>
);
}
}
export default withRouter(connect()(App));
And then my router stuff.
import './views/styles/styles.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import history from './history';
import configureStore from './store';
import registerServiceWorker from './utils/register-service-worker';
import App from './views/app';
import TaskPage from './views/pages/tasks'
const store = configureStore();
const rootElement = document.getElementById('root');
function render(Component) {
console.log('COMPONENT::',Component);
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<Component />
</div>
</ConnectedRouter>
</Provider>,
rootElement
);
}
if (module.hot) {
module.hot.accept('./views/app', () => {
render(require('./views/app').default);
})
}
registerServiceWorker();
I initially get a blank page. But if I make a change to the App page and save it while the app is running, like just a space or line return, something insignificant, I get my tasks page suddenly. It works fine then. I have no errors in my console at any point during this process so I think I have something wrong with my routing somewhere when the app initially loads.
Or maybe it has something to do with this TaskPage.
import React, { Component } from 'react';
import { List } from 'immutable';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { createSelector } from 'reselect';
import { getTaskFilter, getVisibleTasks, tasksActions } from 'src/tasks';
import TaskFilters from '../../components/task-filters';
import TaskForm from '../../components/task-form';
import TaskList from '../../components/task-list';
export class TasksPage extends Component {
static propTypes = {
createTask: PropTypes.func.isRequired,
filterTasks: PropTypes.func.isRequired,
filterType: PropTypes.string.isRequired,
loadTasks: PropTypes.func.isRequired,
location: PropTypes.object.isRequired,
removeTask: PropTypes.func.isRequired,
tasks: PropTypes.instanceOf(List).isRequired,
updateTask: PropTypes.func.isRequired
};
componentWillMount() {
this.props.loadTasks();
this.props.filterTasks(
this.getFilterParam(this.props.location.search)
);
}
componentWillReceiveProps(nextProps) {
if (nextProps.location.search !== this.props.location.search) {
this.props.filterTasks(
this.getFilterParam(nextProps.location.search)
);
}
}
componentWillUnmount() {
// this.props.unloadTasks();
}
getFilterParam(search) {
const params = new URLSearchParams(search);
return params.get('filter');
}
render() {
return (
<div className="g-row">
<div className="g-col">
<TaskForm handleSubmit={this.props.createTask} />
</div>
<div className="g-col">
<TaskFilters filter={this.props.filterType} />
<TaskList
removeTask={this.props.removeTask}
tasks={this.props.tasks}
updateTask={this.props.updateTask}
/>
</div>
</div>
);
}
}
//=====================================
// CONNECT
//-------------------------------------
const mapStateToProps = createSelector(
getTaskFilter,
getVisibleTasks,
(filterType, tasks) => ({
filterType,
tasks
})
);
const mapDispatchToProps = Object.assign(
{},
tasksActions
);
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(TasksPage));
So something with the hotloading or maybe the way I had it setup?? Im not saying its the best answer but it did resolve my problem. If someone can explain this better than I'll happily accept a clearer response on the subject
This should have worked based on the docs. But I commented it out and went back to just using ReactDOM.Render with my . No wrapped Function or . And oddly hotloading still seems to work.
// function render(Component) {
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<App/>
</div>
</ConnectedRouter>
</Provider>,
rootElement
);
// }
// if (module.hot) {
// module.hot.accept('./views/app', () => {
// render(require('./views/app').default);
// })
// }
FYI - Im react-router 4.x, Redux 5.x, React 15.x.

Resources