I'm using React-Native-Navigation with the Context api.
I'm wrapping my screens with a HOC component below.
const ProviderWrap = Comp => props => (
<Provider>
<Comp {...props} />
</Provider>
);
Navigation.registerComponent('app.AuthScreen', () => ProviderWrap(AuthScreen));
Navigation.registerComponent('app.FindPlaceScreen', () => ProviderWrap(FindPlaceScreen));
Navigation.registerComponent('app.SharePlaceScreen', () => ProviderWrap(SharePlaceScreen));
And this is my Provider Component
class Provider extends Component {
state = {
placeName: 'hello',
image: 'https://images.unsplash.com/photo-1534075786808-9b819c51f0b7?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=4dec0c0b139fb398b714a5c8264b4a9a&auto=format&fit=crop&w=934&q=80',
places: [],
}
textInputHandler = (text) => {
this.setState({
placeName: text,
})
}
searchInputHandler = (text) => {
const SearchedPlace = this.state.places.filter(place => {
return place.name.includes(text)
})
this.setState(prevState => {
return {
places: SearchedPlace,
}
})
}
placeSubmitHandler = () => {
if (this.state.placeName) {
this.setState(prevState => {
return {
places: [...prevState.places, {
name: prevState.placeName,
image: prevState.image,
}],
placeName: '',
}
})
} else {
return;
}
}
placeDeleteHandler = (id, deleteModal) => {
const newPlaces = this.state.places.filter((place, index) => {
return index !== id
})
this.setState({
places: newPlaces,
})
deleteModal();
}
render() {
return (
<GlobalContext.Provider value={{
state: this.state,
textInputHandler: this.textInputHandler,
placeSubmitHandler: this.placeSubmitHandler,
placeDeleteHandler: this.placeDeleteHandler,
searchInputHandler: this.searchInputHandler,
}}>
{this.props.children}
</GlobalContext.Provider>
)
}
}
My issue is that The Context state isnt shared between screens. in my context state i have a places array which i add to in the SharePlaceScreen which works fine but when i go over to FindPlaceScreen that context state places is empty. As if i had two separate context for each screen.
Here is an example of singleton Object there are many implementation you cas use es6 class also ... es6 examples
var SingletonState = (function () {
var state;
function createState() {
return {someKey:'what ever'};
}
return {
getState: function () {
if (!state) {
state = createState();
}
return state;
}
};
})();
// usage
var state1 = SingletonState.getState();
var state2 = SingletonState.getState();
console.log("Same state? " + (state1 === state2));
Related
class App extends Component {
constructor(props) {
super(props);
this.state = {
user: null,
userWorkSpecialIds: false,
};
}
isAuthorized = (user) => {
const { user } = this.state;
if (!user) return false;
else {
// check to see if user has special work permit id
this.hasWorkAccount(user);
return user.some((item) => user.email === item.id);
}
}
isLoaded = () => {
const { user } = this.state;
return user != null;
}
hasWorkAccount = () => {
getCustomerList(function(data) { // service gets users work place from firebase
const checkworkerSpecialIds = data.map((item) => {
return {
id: item.w_id,
name: item.w_name,
special_id: item.wspecial_id,
};
});
// checkworkerSpecialIds returns the user list of Ids correctly
console.log("checking for spacial_id : ", checkworkerSpecialIds);
// *** ERROR: ***
this.setState({ userWorkSpecialIds: !this.userWorkSpecialIds})
console.log("never reachs here when I have this.setState({}) ");
});
}
componentDidMount() {
const DataArray = [];
firebaseAppFirestore
.collection("users")
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
myDataArray.push({ id: doc.id, role: doc.role });
});
this.setState({ user: DataArray });
});
}
}
render() {
return (
<UserProvider>
<FirestoreProvider firebase={firebase}>
{this.isLoaded() ? (
this.isAuthorized(firebaseAppAuth.currentUser) ? (
<Router history={browserHistory}>
<Routes
users={this.state.users}
userWorkSpecialIds={this.state.userWorkSpecialIds} <----- Not updating after 1st render
/>
</Router>
) : (
<SignInView/>
)
) : (
<CircularProgress />
)}
</FirestoreProvider>
</UserProvider>
);
}
}
export default withFirebaseAuth({
firebaseAppAuth,
})(App);
I'm stuck on *** ERROR: ***, after I retrieve the checkworkerSpecialIds, should the
this.setState({ userWorkSpecialIds: !this.userWorkSpecialIds}), trigger the component and update userWorkSpecialIds.
I want to trigger the state userWorkSpecialIds updates and update the props
Currently the Routs props just receives does userWorkSpecialIds = false, never gets updated.
I am having a chat web app which is connected to firebase.
When I refresh the page the lastMessage is loaded (as the gif shows), however, for some reason, if the component is otherwise mounted the lastMessage sometimes flickers and disappears afterwards like it is overridden. When I hover over it, and hence update the component, the lastMessage is there.
This is a weird behavior and I spent now days trying different things.
I would be very grateful if someone could take a look as I am really stuck here.
The db setup is that on firestore the chat collection has a sub-collection messages.
App.js
// render property doesn't re-mount the MainContainer on navigation
const MainRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props => (
<MainContainer>
<Component {...props} />
</MainContainer>
)}
/>
);
render() {
return (
...
<MainRoute
path="/chats/one_to_one"
exact
component={OneToOneChatContainer}
/>
// on refresh the firebase user info is retrieved again
class MainContainer extends Component {
componentDidMount() {
const { user, getUserInfo, firebaseAuthRefresh } = this.props;
const { isAuthenticated } = user;
if (isAuthenticated) {
getUserInfo(user.id);
firebaseAuthRefresh();
} else {
history.push("/sign_in");
}
}
render() {
return (
<div>
<Navigation {...this.props} />
<Main {...this.props} />
</div>
);
}
}
Action
// if I set a timeout around fetchResidentsForChat this delay will make the lastMessage appear...so I must have screwed up the state / updating somewhere.
const firebaseAuthRefresh = () => dispatch => {
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
localStorage.setItem("firebaseUid", user.uid);
dispatch(setFirebaseAuthUser({uid: user.uid, email: user.email}))
dispatch(fetchAllFirebaseData(user.projectId));
}
});
};
export const fetchAllFirebaseData = projectId => dispatch => {
const userId = localStorage.getItem("firebaseId");
if (userId) {
dispatch(fetchOneToOneChat(userId));
}
if (projectId) {
// setTimeout(() => {
dispatch(fetchResidentsForChat(projectId));
// }, 100);
...
export const fetchOneToOneChat = userId => dispatch => {
dispatch(requestOneToOneChat());
database
.collection("chat")
.where("userId", "==", userId)
.orderBy("updated_at", "desc")
.onSnapshot(querySnapshot => {
let oneToOne = [];
querySnapshot.forEach(doc => {
let messages = [];
doc.ref
.collection("messages")
.orderBy("created_at")
.onSnapshot(snapshot => {
snapshot.forEach(message => {
messages.push({ id: message.id, ...message.data() });
});
});
oneToOne.push(Object.assign({}, doc.data(), { messages: messages }));
});
dispatch(fetchOneToOneSuccess(oneToOne));
});
};
Reducer
const initialState = {
residents: [],
oneToOne: []
};
function firebaseChat(state = initialState, action) {
switch (action.type) {
case FETCH_RESIDENT_SUCCESS:
return {
...state,
residents: action.payload,
isLoading: false
};
case FETCH_ONE_TO_ONE_CHAT_SUCCESS:
return {
...state,
oneToOne: action.payload,
isLoading: false
};
...
Main.js
// ...
render() {
return (...
<div>{React.cloneElement(children, this.props)}</div>
)
}
OneToOne Chat Container
// without firebaseAuthRefresh I don't get any chat displayed. Actually I thought having it inside MainContainer would be sufficient and subscribe here only to the chat data with fetchOneToOneChat.
// Maybe someone has a better idea or point me in another direction.
class OneToOneChatContainer extends Component {
componentDidMount() {
const { firebaseAuthRefresh, firebaseData, fetchOneToOneChat } = this.props;
const { user } = firebaseData;
firebaseAuthRefresh();
fetchOneToOneChat(user.id || localStorage.getItem("firebaseId"));
}
render() {
return (
<OneToOneChat {...this.props} />
);
}
}
export default class OneToOneChat extends Component {
render() {
<MessageNavigation
firebaseChat={firebaseChat}
firebaseData={firebaseData}
residents={firebaseChat.residents}
onClick={this.selectUser}
selectedUserId={selectedUser && selectedUser.residentId}
/>
}
}
export default class MessageNavigation extends Component {
render() {
const {
onClick,
selectedUserId,
firebaseChat,
firebaseData
} = this.props;
<RenderResidentsChatNavigation
searchChat={this.searchChat}
residents={residents}
onClick={onClick}
firebaseData={firebaseData}
firebaseChat={firebaseChat}
selectedUserId={selectedUserId}
/>
}
}
const RenderResidentsChatNavigation = ({
residents,
searchChat,
selectedUserId,
onClick,
firebaseData,
firebaseChat
}) => (
<div>
{firebaseChat.oneToOne.map(chat => {
const user = residents.find(
resident => chat.residentId === resident.residentId
);
const selected = selectedUserId == chat.residentId;
if (!!user) {
return (
<MessageNavigationItem
id={chat.residentId}
key={chat.residentId}
chat={chat}
onClick={onClick}
selected={selected}
user={user}
firebaseData={firebaseData}
/>
);
}
})}
{residents.map(user => {
const selected = selectedUserId == user.residentId;
const chat = firebaseChat.oneToOne.find(
chat => chat.residentId === user.residentId
);
if (_isEmpty(chat)) {
return (
<MessageNavigationItem
id={user.residentId}
key={user.residentId}
chat={chat}
onClick={onClick}
selected={selected}
user={user}
firebaseData={firebaseData}
/>
);
}
})}
</div>
}
}
And lastly the item where the lastMessage is actually displayed
export default class MessageNavigationItem extends Component {
render() {
const { hovered } = this.state;
const { user, selected, chat, isGroupChat, group, id } = this.props;
const { messages } = chat;
const item = isGroupChat ? group : user;
const lastMessage = _last(messages);
return (
<div>
{`${user.firstName} (${user.unit})`}
{lastMessage && lastMessage.content}
</div>
)
}
In the end it was an async setup issue.
In the action 'messages' are a sub-collection of the collection 'chats'.
To retrieve them it is an async operation.
When I returned a Promise for the messages of each chat and awaited for it before I run the success dispatch function, the messages are shown as expected.
This is surely very simple but I dont understand how it works. I try to bind checkbox with state and with state display different string. It is in React with Redux. The code below (bold font)
container:
class DropingList extends Component {
**conditionHandler() {
if(this.props.pet === 'cat'){
return "YEAH!!!"
}else {return null;}**
}
render() {
return (
<div>
<AddHimHer
click={this.props.onAddMan}
/>
{ this.props.pers.map(per =>(
<NewPerson
key={per.id}
click={() => this.props.onManDown(per.id)}
name={per.name}
age={per.age}
**animal={this.conditionHandler(this.props.pet)}**
/>
))
}
</div>
)
}
}
const mapStateToProps = state => {
return {
pers: state.persons
}
}
const mapDispatchToProps = dispatch => {
return {
onAddMan: (name,age,**pet**) => dispatch({type:actionTypes.ADD_MAN, data: {nam: name, ag: age, **superp: pet**}}),
onManDown: (id) => dispatch({type:actionTypes.MAN_DOWN, Id: id})
}
}
export default connect(mapStateToProps,mapDispatchToProps)(DropingList);
component:
const NewPerson = (props) => (
<div onClick={props.click}>
<h1>Is {props.name} a SUPERHERO? ? ???</h1>
<h2>He is {props.age} years old</h2>
**<h1>{props.animal}</h1>**
</div>
);
export default NewPerson;
reducer:
const initState = {
persons: []
}
const personReducer = (state = initState,action) => {
switch (action.type) {
case actionTypes.ADD_MAN:
const newMan = {
id: Math.random(),
name: action.data.nam,
age: action.data.ag,
**pet: action.data.superp**
};
return {
...state,
persons: state.persons.concat(newMan)
};
case actionTypes.MAN_DOWN:
return {
...state,
persons: state.persons.filter(person => person.id !== action.Id)
};
}
return state;
};
export default personReducer;
I am still newbe in React and Redux. I think I have ommited something.
Could you tell me whats wrong with my code?
Issue is pet is the part of the object (each object of the array), not a separate prop so you need to use per.pet in map callback function, like this:
{this.props.pers.map(per =>(
<NewPerson
key={per.id}
click={() => this.props.onManDown(per.id)}
name={per.name}
age={per.age}
animal={this.conditionHandler(per.pet)} // here
/>
))}
Now you are passing the pet value to function conditionHandler, so no need to use this.props.pet inside that directly use pet, like this:
conditionHandler(pet) {
if (pet === 'cat') {
return "YEAH!!!"
} else {
return null;
}
}
I'm integrating recaptcha to my react app and I'm having this error: "Missing required parameters: sitekey" when I use the render method of grecaptch even though I have properly included the sitekey in to the parameters.
Here is my code for reference:
class ReCaptcha extends React.Component {
componentDidMount() {
this.callbackName = 'g-lf-callback';
window[this.callbackName] = this.props.callback;
if(window.grecaptcha) {
this.renderRecaptcha();
} else {
this.loadRecaptchaScript();
}
}
componentWillUnmount() {
delete window['rconload'];
delete window[this.callbackName];
}
loadRecaptchaScript() {
window['rconload'] = () => {
this.renderRecaptcha();
};
let url = 'https://www.google.com/recaptcha/api.js?onload=rconload&render=explicit';
loadScript(url, '', 'recaptcha', true, true)
.then( () => {})
.catch( () => {});
}
renderRecaptcha = () => {
if(this.container) {
let parameters = {
sitekey: process.env.MY_SITEKEY,
size: 'invisible',
badge: null,
callback: 'g-lf-callback'
};
const recaptchaId = window.grecaptcha.render(this.container, parameters);
this.execute = () => window.grecaptcha.execute(recaptchaId);
this.reset = () => window.grecaptcha.reset(recaptchaId);
this.getResponse = () => window.grecaptcha.getResponse(recaptchaId);
}
}
onClick = () => {
this.execute();
}
render() {
let { callback, label, className, ...btnProps } = this.props;
return (
<Button
{ ...btnProps }
className={ className }
onClick={ this.onClick }
ref = { ref => this.container = ref }
>
{ label }
</Button>
)
}
}
I have also set the render parameter of recaptcha url to explicit
https://www.google.com/recaptcha/api.js?onload=rconload&render=explicit
Onload callback:
window['rconload'] = () => {
this.renderRecaptcha();
};
I have two react components which are ProgramSearchBox and DualBox which are generic and wrapper components of predefined npm packages AutoSuggest and DualListBox respectively.
My task to achieve is Based on the value from ProgramSearchBox, I have to list the set values in the DualListBox.
So, If user select a Program from ProgramSearchBox, then I will call API by passing the ProgramId and fetch the set of result values and have to bind them in the DualListBox.
I will get the user selected ProgramID from the ProgramSearchBox as a prop in DualBox component render method.
How to dispatch an action (call a function) from render function in DualBox component by passing the ProgramId?
If I call a method from render function in DualBox, that is becoming Infinite loop!
Here is DualBox component:
//DualBox.js
class DualBox extends React.Component {
constructor() {
super();
this.state = { selected: [] };
this.onChange = this.onChange.bind(this);
this.options = [ ];
}
onChange(selected) {
selected(selected);
}
updateOptions()
{
console.log("Update Option method called :" + this.props.traineesList );
this.options = [{ value: 'luna', label: 'Moon' }, { value: 'phobos', label: 'Phobos' }];
//this.options = this.props.traineeList.map( (value,id) => )
}
render() {
const {ProgramID} = this.props; // HERE I GET ProgramID AS PROP FROM AN ANOTHER COMPONENT
const {selected} = this.state;
if(ProgramID !== "") // BASED ON THIS ProgramID VALUE, I NEED TO DISPATCH AN ACTION.
{
{this.updateProgramId(ProgramID)} // THIS IS CAUSING INFINITE LOOP
{this.updateOptions}
console.log("Program Id came to dualbox:" +ProgramID);
return <DualListBox options={this.options} selected={selected} onChange={this.onChange}
canFilter
filterCallback={(option, filterInput) => {
if (filterInput === '') {
return true;
}
return (new RegExp(filterInput, 'i')).test(option.label);
}}
filterPlaceholder="Filter..."
/>;
}
else
{
console.log("Program Id didn't come to dualbox");
return <DualListBox options={this.options} selected={selected} onChange={this.onChange}
canFilter
filterCallback={(option, filterInput) => {
if (filterInput === '') {
return true;
}
return (new RegExp(filterInput, 'i')).test(option.label);
}}
filterPlaceholder="Filter..."
/>;
}
}
}
function mapStateToProps(state, ownProps) {
return {
traineesList: state.traineesList
};
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
updateProgramId: bindActionCreators(( {ProgramID}) => dualBoxActions.getTraineesList(ProgramID), dispatch)
};
}
export default connect(mapStateToProps,mapDispatchToProps)(DualBox);
Here is the ProgramSearchBox component:
function renderSuggestion(suggestion) {
return (
<ul>
<li>{suggestion.Program}</li>
</ul>
);
}
class ProgramSearchBox extends React.Component {
constructor(props) {
super(props);
}
render() {
const { value, suggestions, onChange, onSuggestionSelected} = this.props;
const inputProps = {
placeholder: "Look Up",
value,
onChange: (event, { newValue, method }) => {
this.setState({
value: newValue
});
console.log("onChange: " + JSON.stringify(newValue) );
onChange(newValue);
}
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.props.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.props.onSuggestionsClearRequested}
onSuggestionSelected={
(event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) => {
console.log("onSuggestionSelected: " + JSON.stringify(suggestion) );
onSuggestionSelected(suggestion);
}
}
getSuggestionValue={(suggestion) => suggestion.Program}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
theme={theme}
/>
);
}
}
function mapStateToProps(state, ownProps) {
return {
suggestions: state.results
};
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onSuggestionsFetchRequested: bindActionCreators(({ value }) => searchActions.getProgramSuggestions(value), dispatch),
onSuggestionsClearRequested: bindActionCreators(() => searchActions.clearSuggestions(), dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ProgramSearchBox);
Don't call other functions in render() method. Render method is responsible only for rendering views, it can be called many times and it should be as pure as possible.
Updated answer (2019-11-21)
Use componentDidUpdate(prevProps) lifecycle function to react to prop changes.
It will look something like this:
componentDidUpdate(prevProps) {
if (this.props.ProgramID !== '' && prevProps.ProgramID !== this.props.ProgramID) {
this.updateProgramId(this.props.ProgramID)
}
}
Old answer
To do actions depending on props changing, use componentWillReceiveProps(nextProps) lifecycle function.
It will look something like this:
componentWillReceiveProps(nextProps) {
if (nextProps.ProgramID !== '' && this.props.ProgramID !== nextProps.ProgramID) {
this.updateProgramId(ProgramID)
}
}
After calling this.updateProgramId(ProgramID) props will update and render method will be called.
More info about ReactJS lifecycle:
https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops