Props not being passed - React Native - javascript

I am using react-native-modalbox to show a modal and save data as a result.
When I save the data, my modal has access to the parent flat list so I can call a getData() function correctly, and the flat list reflects the latest update:
Modal - saveItem() is executed when a save button is pressed.
saveItem = async () => {
...
this.props.parentFlatList.getData();
this.props.progress.getData(); //This function call returns an error
this.closeModal();
};
Parent - the onPressAdd function opens the modalbox
constructor(props) {
super(props);
this.state = {
...
};
this.onPressAdd = this.onPressAdd.bind(this);
}
...
onPressAdd = () => {
this.refs.addFoodModal.showAddFoodModal();
}
<AddFoodModal ref={'addFoodModal'} parentFlatList={this} />
However, when I try to link the modal to another parent I receive this error:
Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'getData' of undefined
I simply want the modal to call the getData() functions in both parents so they both receive the updated data in their states.
Another Parent - this does not open the modal but I assumed it could pass itself down as props as the other parent does?
<AddFoodModal ref={'addFoodModal'} progress={this} />

Not sure where you get progress, if I understand correctly, you can pass progress to ur parent component as a props like <Parent progress={progress} />, then in ur child modal component you can do .
Also passing this down to child component is not a good practice, you should only pass what you actually need to ur child component to avoid unnecessary re-rendering, which will affect performance. In your code, you should pass getData down to the child component as a props, not this.

Related

Vue calling parent component function when child component function completes

In Vue I have a main component that houses a child component which is loaded on the page with a button and the button triggers saveTaskComment(). This works perfectly, and I can get into the .finally portion of the child components function. HOwever, when it completes and gets to that point I want to make a call back to the parent component to call the method getInformation again. The way I have it right now that doesn't work so I guess $parent isn't correct in this case.
What do I need to do to get the method in teh childComponent to call the original function
mainComponent
methods: {
getInformation() {
this.$root.$emit('fetchCommentsEvent');
},
}
childComponent
saveTaskComment() {
/*function completes and gets to this step fine*/
.finally(() => {
this.$parent.getInformation();
});
}
I've made a sample on CodeSandbox to illustrate what I said in the comment.
The key point to take away here is when you insert the Child's template into your Parent's template, you want to listen to certain event and call getInformation() when the event is emitted.
<Child #foo="getInformation()">This is child.</Child>
In order to emit this foo event back to the parent, you simply do this.$emit(eventName, optionalData) from the Child component.
Since we're listening for foo event, you want to emit it like so.
this.$emit("foo");
To emit some method from a child component, you have to pass that method to the child.
MainComponent.vue:
<child-comp #getInformation="getInformation" />
ChildComponent.vue:
.finally(() => {
this.$emit('getInformation')
});
and in case you want to pass some data to the parent method, you can do that by
this.$emit('getInformation', dataVariable)

React - Call setState in parent when child is called

I am building a blog in react where I get the data from a JSON-API and render it dynamically. I call setState in my app.js to get the data from JSON via axios and route with match.params to the post pages(childs). This works fine, BUT if I call the child (URL: ../blog/post1) in a seperate window it doesnt get rendered. It works if I hardcode the state.
So, I see the issue, what would be the best way to fix it?
Parent:
class App extends Component {
constructor(props) {
super();
this.state = {
posts: []
}
getPosts() {
axios.get('APIURL')
.then(res => {
let data = res.data.posts;
this.setState({
posts: data
})
})
}
componentDidMount = () => this.getPosts()
Child:
UPDATE - Found the error:
The component threw an error, because the props were empty. This was because the axios getData took some time.
Solution: I added a ternary operator to check if axios is done and displayed a css-spinner while loading. So no error in component.
Dynamic Routing works like a charme.
You can do this with binding. You would need to write a function like
setPosts(posts) {
this.setState({posts});
}
in the parent, and then in the parent, bind it in the constructor, like so.
this.setPosts = this.setPosts.bind(this);
When you do this, you're attaching setPosts to the scope of the parent, so that all mentions of this in the function refer to the parent's this instead of the child's this. Then all you need to do is pass the function down to the child in the render
<Child setPosts={this.setPosts} />
and access that method in the child with
this.props.setPosts( /*post array goes here */ );
This can apply to your getPosts method as well, binding it to the parent class and passing it down to the Child.
When you hit the /blog/post1 url, it renders only that page. The App component is not loaded. If you navigate from the App page, all the loading has been done and you have the post data in the state of the child component.
Please refer to this SO question. This should answer your question.

ReactJS - setState fails to update property value

I have a property name in a React component. Using setState I am trying to modify this property. But assigning a new value to this property inside setState has no effect. Please find below my sample code.
export const Test = ({
name,
changeState = function (newName) {
this.setState({name: newName}, () => console.log('Name after setState # ' + name)); //prints old value
console.log(name); // Doesn't reflect changes. Prints old name
}
}) =>
(
<div>Some data</div>
)
User action will trigger a call to changeState(newName). I am calling setState inside changeState function.
After calling setState if I print the name variable to console it still holds old value.
How can I make setState assign a new value to name?
I am aware that setState is asynchronous and update to property may reflect after a delay. But in case of example code above name variable is never updated even after a delay.
I have implemented componentWillReceiveProps(nextProps) method and it gets called but it always receives old name. So I don't think the issue is related to setState being asynchronous.
I have created an example app to demonstrate the issue I am facing. The example app runs fine locally and I can reproduce the issue. But I am not being able to get the same example app code working in codepen. it's giving me some 'unexpected token' errors. But I hope looking at the code will help understand my issue better. The code is based on existing application structure.
Codepen example here.
In the code I have a Parent and two children Child1 and Child2. In Parent I have a function changeState defined which I am passing to Child1 as property. And to Child2 I am passing a 'name' property from Parent.
Clicking on 'Change Name' button in Child1 triggers a call to changeState function of Parent. Initial value of name in Parent is 'Robert'. changeState is invoked from Child1 with new name value of 'Tom'. But in changeState function assigning new value to 'name' using setState has no effect. I am calling a function to print the 'name' after setState has completed but it prints old name value and NOT the new one assigned in setState.
You are using stateless component, there's for, there is no state so the setState function doesn't affect anything.
there are 2 options to deal with it:
the easiest one, but most likely not the best option, just change your component to regular component:
export class Test1 extends React.componnent {
...
(the rest of your component)
}
the second option (usually a better one in my option) is instead of changing the state for the component, get an event from the parent component, and call the event where you wanted to call the setState, the event would contain an updating the value as requested, and the child component would receive it as prop, and your component wouldn't have to change to Container (a component with state)
Good luck!

Trouble with printing parent state from child (ReactJS)

I'm attempting to use a parent to control an editor component and a save component. The parent component has these functions:
constructor() {
super();
this.state = {
code: "",
current_program: 'new'
}
}
updateCode(event) {
this.setState({
code: event
});
}
save() {
console.log(this.state.code);
}
In it's render component, I have this:
<IDE code={this.state.code} updateCode={this.updateCode}/>
<Browser save={this.save.bind(this)} programs={this.props.programs} />
The IDE successfully calls update, and when I log the output from the updateCode function in the parent, it works properly. But... In my browser component, I have the following:
<Button className="width-30" bsStyle="primary" onClick={() => this.props.save()}>
<Glyphicon glyph="save" /> Save
</Button>
On click, it prints "", does this have to do with the fact that I bound "this" before the code in the parent state was updated? Is it just printing the old state? How can I make it update? Thanks.
Edit: I'm calling this from the IDE component: onChange={this.props.updateCode.bind(this)}
Solved it: I was binding the state of the CHILD in the IDE component, which meant that was what was updating, changing the implementation of the IDE component in the parent to the following: <IDE code={this.state.code} updateCode={this.updateCode.bind(this)}/>, allowed the states to update properly

How to allow child component to react to a routing event before the parent component?

I am using react, react-router & redux. The structure of my app is such:
CoreLayout
-> <MaterialToolbar /> (contains back button)
-> {children} (react-router)
When the user presses the back button, which is normally handled by the CoreLayout, I would like the current child component to handle the back button instead of the parent. (In my case, I would like the current view to check if its data has been modified, and pop up an 'Are you sure you wish to cancel?' box before actually going back.) If the child does not wish to handle this, the parent will do it's thing.
Another example would be allowing a childview to set the title in the toolbar.
My reading has told me that accessing a component through a ref and calling a method on it is not the react way -- this is also made a bit more difficult since I am using redux-connect. What is the correct way to implement this behavior?
This is how I would do it, assuming you mean your navigation back button (and not the browser back button):
class CoreLayout extends Component {
handleBack () {
//... use router to go back
}
render () {
return <div>
<MaterialToolbar />
{React.children.map(this.props.children, child => React.cloneElement(child, { onBack: this.handleBack }))}
</div>
}
}
class Child extends Component {
handleBackButtonClick () {
// Here perform the logic to decide what to do
if (dataHasBeenModifiedAndConfirmed) {
// Yes, user wants to go back, call function passed by the parent
this.props.onBack()
} else {
// User didn't confirm, decide what to do
}
}
render () {
return <div onClick={this.handleBackButtonClick.bind(this)}>
Go Back
</div>
}
}
You simply pass a function from the parent to the child via props. Then in the child you can implement the logic to check if you really want to delegate the work to the parent component.
Since you use react-router and your children are passed to your parent component through this.props.children, to pass the onBack function you need to map the children and use React.cloneElement to pass your props (see this answer if you need more details on that: React.cloneElement: pass new children or copy props.children?).
Edit:
Since it seems you want to let the children decide, you can do it this way (using refs):
class CoreLayout extends Component {
constructor () {
super()
this.childRefs = {};
}
handleBack () {
for (let refKey in Object.keys(this.childRefs) {
const refCmp = this.childRefs[refKey];
// You can also pass extra args to refCmp.shouldGoBack if you need to
if (typeof refCmp.shouldGoBack === 'function' && !refCmp.shouldGoBack()) {
return false;
}
}
// No child requested to handle the back button, continue here...
}
render () {
return <div>
<MaterialToolbar />
{React.children.map(this.props.children, (child, n) => React.cloneElement(child, {
ref: cmp => { this.childRefs[n] = cmp; }
}))}
</div>
}
}
class Child extends Component {
shouldGoBack () {
// Return true/false if you do/don't want to actually go back
return true
}
render () {
return <div>
Some content here
</div>
}
}
This is a bit more convoluted as normally with React it's easier/more idiomatic to have a "smart" parent that decides based on the state, but given your specific case (back button in the parent and the logic in the children) and without reimplementing a few other things, I think using refs this way is fine.
Alternatively (with Redux) as the other answer suggested, you would need to set something in the Redux state from the children that you can use in the parent to decide what to do.
Hope it's helpful.
I don't think there is a correct way to solve this problem, but there are many ways. If I understand your problem correctly, most of the time the back button onClick handler will be handled within CoreLayout, but when a particular child is rendered that child will handle the onClick event. This is an interesting problem, because the ability to change the functionality of the back button needs to be globally available, or at very least available in CoreLayout and the particular child component.
I have not used redux, but I have used Fluxible and am familar with the Flux architecture and the pub/sub pattern.
Perhaps you can utilize your redux store to determine the functionality of your back button. And your CoreLayout component would handle rendering the prompt. There is a bug with the following code, but I thought I would not delete my answer for the sake of giving you an idea of what I am talking about and hopefully the following code does that. You would need to think through the logic to get this working correctly, but the idea is there. Use the store to determine what the back button will do.
//Core Layout
componentDidMount() {
store.subscribe(() => {
const state = store.getState();
// backFunction is a string correlating to name of function in Core Layout Component
if(state.backFunction) {
// lets assume backFunction is 'showModal'. Execute this.showModal()
// and let it handle the rest.
this[state.backFunction]();
// set function to false so its not called everytime the store updates.
store.dispatch({ type: 'UPDATE_BACK_FUNCTION', data: false})
}
})
}
showModal() {
// update state, show modal in Core Layout
if(userWantsToGoBack) {
this.onBack();
// update store backFunction to be the default onBack
store.dispatch({ type: 'UPDATE_BACK_FUNCTION', data: 'onBack'})
// if they don't want to go back, hide the modal
} else {
// hide modal
}
}
onBack() {
// handle going back when modal doesn't need to be shown
}
The next step is to update your store when the child component mounts
// Child component
componentDidMount(){
// update backFunction so when back button is clicked the appropriate function will be called from CoreLayout
store.dispatch({ type: 'UPDATE_BACK_FUNCTION', data: 'showModal'});
}
This way you don't need to worry about passing any function to your child component you let the state of the store determine which function CoreLayout will call.

Categories

Resources