ReactJS - Pass Updated Value To Sub-Component Method - reactjs

I'm working on an environment that is basically set up with a Main Component like this:
class MainComponent extends Component {
constructor(props) {
super(props);
this.state = {
selectedValues: []
};
}
render() {
const { selectedValues } = this.state;
return (
// Other components
<SubComponent selectedValues = {selectedValues} />
// Other components
);
}
}
export default MainComponent;
And a Sub Component like this:
class SubComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isExporting: false,
selectedValues: props.selectedValues
};
}
performTask = () => {
this.setState({ isWorking: true });
const { selectedValues } = this.state;
console.log(`Selected Values: ${selectedValues}`);
fetch('/api/work', {
method: 'GET'
})
.then(res => res.json())
.then((result) => {
// Handle the result
this.setState({ isWorking: false });
})
.catch((error) => {
console.log(error);
this.setState({ isWorking: false });
});
};
render() {
const { isWorking } = this.state;
return (
<Button
bsStyle="primary"
disabled={isWorking}
onClick={() => this.performTask()}
>
{isWorking ? 'Working...' : 'Work'}
</Button>
);
}
}
SubComponent.propTypes = {
selectedValues: PropTypes.arrayOf(PropTypes.string)
};
SubComponent.defaultProps = {
selectedValues: []
};
export default SubComponent;
In the Main Component, there are other components at work that can change the selectedValues. The functionality I'd like to see is that when the performTask method fires, it has the most recent and up to date list of selectedValues. With my current setup, selectedValues is always an empty list. No matter how many values actually get selected in the Main Component, the list never seems to change in the Sub Component.
Is there a simple way to do this?

I would suggest you 2 of the following methods to check this problem:
Maybe the state.selectedItems doesn't change at all. You only declare it in the contractor but the value remains, since you didn't setState with other value to it. Maybe it will work if you will refer to this.props.selectedItems instead.
Try to add the function component WillReceiveProps(newProps) to the sub component and check the value there.
If this method doesn't call, it means the selectedItems doesnt change.
Update if some of it works.
Good luck.

selectedValues in SubComponent state has not updated since it was set in SubComponent constructor. You may need to call setState again in componentWillReceivedProps in SubComponent

Related

How can I chain asynchronous Firebase updates in my React app?

React & Firebase newbie here. I have a React component that needs to look up some stuff in Firebase before rendering. My database design requires first getting the correct doohick ids and subsequently looking up the doohick details, but I'm not sure how to do that with the asynchronous nature of Firebase database access. This doesn't work:
class Widget extends React.Component {
componentDidMount() {
firebase.database().ref(`/users/${username}/doohick-ids`).on('value', snapshot => {
this.setState({doohick_ids: doohick_ids});
});
this.state.doohick_ids.forEach(id => {
// ids don't actually exist at this point outside the callback
firebase.database().ref(`/doohick-details/${id}`).on('value', snapshot => {
// update state
});
});
render() {
if (this.state.doohick-ids) {
return null;
} else {
// render the Doohick subcomponents
}
}
}
I can think of a few solutions here, but none that I like. What's the recommended way to chain together Firebase calls, or perhaps redesign this to eliminate the problem?
I think you should split one component Widget to two WidgetList and WidgetItem.
WidgetItem
subscribe and unsubscribe to firebase.database().ref(/doohick-details/${id})
class WidgetItem extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
}
constructor(props) {
super(props);
this.state = {};
this.dbRef = null;
this.onValueChange = this.onValueChange.bind(this);
}
componentDidMount() {
const { id } = this.props;
this.dbRef = firebase.database().ref(`/doohick-details/${id}`);
this.dbRef.on('value', this.onValueChange);
}
componentWillUnmount() {
this.dbRef.off('value', this.onValueChange);
}
onValueChange(dataSnapshot) {
// update state
this.setState(dataSnapshot);
}
render() {
return (
<pre>{JSON.stringify(this.state, null, 2)}</pre>
);
}
}
WidgetList
subscribe and unsubscribe to firebase.database().ref(/users/${username}/doohick-ids)
class WidgetItem extends React.Component {
constructor(props) {
super(props);
this.state = { doohick_ids: [] };
this.dbRef = null;
this.onValueChange = this.onValueChange.bind(this);
}
componentDidMount() {
// Note: I've just copied your example. `username` is undefined.
this.dbRef = firebase.database().ref(`/users/${username}/doohick-ids`);
this.dbRef.on('value', this.onValueChange);
}
componentWillUnmount() {
this.dbRef.off('value', this.onValueChange);
}
onValueChange(dataSnapshot) {
this.setState({ doohick_ids: dataSnapshot });
}
render() {
const { doohick_ids } = this.state;
if (doohick_ids.length === 0) {
return 'Loading...';
}
return (
<React.Fragment>
{doohick_ids.map(id => <WidgetItem key={id} id={id} />)}
</React.Fragment>
);
}
}
And code that requires the data from the database needs to be inside the callback that is invoked when that data is available. Code outside of the callback is not going to have the right data.
So:
firebase.database().ref(`/users/${username}/doohick-ids`).on('value', snapshot => {
this.setState({doohick_ids: doohick_ids});
doohick_ids.forEach(id => {
// ids don't actually exist at this point outside the callback
firebase.database().ref(`/doohick-details/${id}`).on('value', snapshot => {
// update state
});
});
});
There's many optimizations possible here, but they all boil down to the code being inside the callback and updating the state when a value comes from the database.

Want to get data in array from API in React Js

I want to get data in array from the API but not able to find the exact solution and i am new to React.js
I am trying to get the data in temp array from the API but not able to figure it out how to use new state as i am already using one setState in componentDidMount method.
Code till componentDidMount method:
class Apiapp extends Component{
constructor(){
super()
this.state = {
loading:true,
characters:{}
}
}
componentDidMount(){
// This means we can use the setState method as many times are we can depending on what
type of methods are we using
// this.setState({
// loading:true
// })
fetch("https://pokeapi.co/api/v2/pokemon/5")
.then(response => response.json())
.then(data => {
let tmpArray = []
for (var i = 0; i < data.game_indices.length; i++) {
tmpArray.push(data.game_indices[i])
}
console.log(data)
this.setState({
loading:false,
characters:data
})
this.setState({
loading:false,
arrCharacters:tmpArray
})
})
}
Code of render method:
render() {
let text = this.state.loading ? <h2>Loading...</h2> : <div><h2>
{this.state.characters.name}
</h2>,<h2>{this.state.arrCharacters.name}</h2></div>
// <h2>{this.state.characters.game_indices[0].version.name}</h2>
return(<div>{text}</div>)
}
}
I am trying to get all the names that is in "game_indices".
API link: https://pokeapi.co/api/v2/pokemon/ditto
Don't overcomplicate things
import React, { Component } from 'react';
class ApiApp extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
characters: {},
};
}
async componentDidMount() {
const data = await fetch('https://pokeapi.co/api/v2/pokemon/5').then((response) => response.json());
this.setState({ characters: data.game_indices, loading: false });
}
render() {
return <div>{this.state.loading ? <h2>Loading...</h2> : this.state.characters.map((i) => i.version.name)}</div>;
}
}
I'm not too sure what data you are trying to display - its not that clear from the question
There are cleaner ways to achieve the same result. However, I'd rather explain what it is wrong with your code:
Check the comments below in your code
import { Component } from 'react'
class App extends Component {
constructor() {
super()
this.state = {
loading: true,
characters: {},
}
}
componentDidMount() {
this.setState({
loading: true,
})
fetch('https://pokeapi.co/api/v2/pokemon/5')
.then((response) => response.json())
.then((data) => {
let tmpArray = []
for (var i = 0; i < data.game_indices.length; i++) {
tmpArray.push(data.game_indices[i])
}
this.setState({
loading: false,
characters: data,
})
this.setState({
loading: false,
arrCharacters: tmpArray,
})
})
}
// Code of render method:
render() {
let text = this.state.loading ? (
<h2>Loading...</h2>
) : (
<div>
<h2>{this.state.characters.name}</h2>,
{/* 1 - When the page first loads "arrCharacters" is undefined.
Therefore you need to add a condition to make sure it is not undefined.
2- You need to loop through all elements to display the name for each of them.
For that, you can use the js array method map.
3- When you display a list, you must use a unique key as attribute.
4 - After you need to check where the data you want to display lives.
In your case, it is inside an obj version. So you access it with "." or "[]"
*/}
{this.state.arrCharacters &&
this.state.arrCharacters.map((char) => (
<h2 key={char.version.name}>{char.version.name}</h2>
))}
</div>
)
return <div>{text}</div>
}
}
export default App

Error: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application

I'm getting the above error and I don't know how to handle it.
I got a component. And in the render() i'm looping through an array and placing another component and parsing a value to that component like this:
render() {
let allProducts = this.state.products.map((product, i) => {
return (
<div key={product.article}>
...
<PriceStock value={product.article} />
...
</div>
)
})
}
In the PriceStock component i'm fetching some data with axios like the code below:
export default class PriceStock extends React.Component {
constructor(props) {
super(props);
this.state = ({
buttoprice: ''
})
this.getPriceAndStock = this.getPriceAndStock.bind(this)
}
getPriceAndStock(articleNo) {
return axios.post('LINK_TO_URL', {
articleNo: articleNo
}).then(result => {
return result.data
})
}
async componentDidMount() {
let pricestock;
pricestock = await this.getPriceAndStock(this.props.value)
let bruttoPrice = PRICE_TO_PARSE_TO_THE_STATE;
this.setState({ buttoprice: bruttoPrice })
}
render() {
return (
<div >
{this.state.buttoprice}
</div>
);
}
}
The error seems to happen when I try to setState in the componentDidMount, any suggestions?
this is an error occurs because you are updating state before it gets initialized
perform your loading activities in the constructor it is the right way to do it
getPriceAndStock(orderNumber, articleNo) {
return axios.post('LINK_TO_URL', {
orderNr: orderNumber, vareNr: articleNo
}).then(result => {
return result.data
})
}
constructor() {
this.getPriceAndStock(this.props.value)
.then(pricestock=>{
let bruttoPrice = PRICE_TO_PARSE_TO_THE_STATE;
this.state({ buttoprice: bruttoPrice })
})
.catch(console.log)
}
Found the answear in this question: https://github.com/material-components/material-components-web-react/issues/434
It's remindend me a little bit about the comment with another stackoverflow question.

How to force children rerendering after axios call in React?

I'm working on a form with interactive inputs. They have to actualise themselves with information into parent state.
I use Axios to get the data to show, getting them from an external API. I tried to set default values, but they never actualise with newer values.
class Form extends React.Component {
getData() {
axios.get('http://xxx/getform/').then(
res => this.setState(res.data)
);
}
componentDidMount() {
this.getData();
setInterval(() => {
this.getData();
}, 36000000)
}
render() {
return (
<div>
<form>
<DatePicker />
</form>
</div>
)
}
}
class DatePicker extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: new Date(),
runMin: new Date(),
runMax: new Date()
};
}
getDate() {
console.log('DAD');
try { // if axios didn't finish, to avoid undefined
this.setState({
runMin: super.state.RunMin,
runMax: super.state.RunMax})
} catch (e) {
this.setState({
runMin: new Date(),
runMax: new Date()})
}
}
componentDidMount() {
this.getDate();
this.setState({selected: this.state.runMax});
}
render() {
return (<div></div>);
}
}
Actually after axios call, the children doesn't rerender. I separated the call for axios and the component using it, because the Form component do a single call for multiple children (not displayed here), and they read the parent's state to render.
Firstly, you should not access the parents state using super and instead pass the required value as props
Secondly, componentDidMount lifecycle is executed on initial mount and hence the logic within it won't execute when the parent state updates.
The correct way to handle your case would be
class Form extends React.Component {
state = {
RunMin: new Date(),
RunMax: new Date()
}
getData() {
axios.get('http://xxx/getform/').then(
res => this.setState({RunMin: res.data.RunMin, RunMax: res.data.RunMax})
);
}
componentDidMount() {
this.getData();
setInterval(() => {
this.getData();
}, 36000000)
}
render() {
return (
<div>
<form>
<DatePicker runMin={this.state.RunMin} runMax={this.state.RunMax}/>
</form>
</div>
)
}
}
class DatePicker extends React.Component {
render() {
console.log(this.props.runMin, this.props.runMax);
return (<div></div>);
}
}
The way you are setting the state is incorrect
Change
this.setState(res.data);
To
this.setState({data: res.data});
You need to set the response to a state field you have in component and make sure you pass the data to the child component

componentDidMount not called when Route with a different param is called

i'm rendering "Details" component in a callback in my UsersListContainer like this:
class UsersListContainer extends Component {
goToUserById(id) {
if (!id) { return false; }
this.props.history.push(`/users/${id}`);
}
render() {
return (
<UserList
goToUser={(id) => this.goToUserById(id)}/>
);
}
}
My "Details" container:
class UserDetailsContainer extends Component {
componentDidMount() {
this.props.getUserDetails(this.props.match.params.id);
}
render() {
return (
<UserDetails user={this.props.selectedUser}/>
);
}
}
const mapDispatchToProps = dispatch => {
return {
getUserDetails: id => dispatch(getUser(id))
};
};
const mapStateToProps = (state) => ({
selectedUser: state.user.selectedUser
});
And in my presentational "User" component I display a set of data from redux store like this:
class UserDetails extends Component {
constructor(props) {
super(props);
this.state = {
name: this.props.user.name,
address: this.props.user.name,
workingHours: this.props.user.workingHours,
phone: this.props.user.phone
};
}
I'm not displaying component props directly and I use state because they are meant to be edited. This works, but the problem is that all these props are not updating simultaneously with component load which means when I select user for the first time it displays the right info, then I switch back to "/users" to choose another, and his props remain the same as props of the previous user. I tried componentWillUnmount to clear the data but it didn't work
Solved this by using lodash lib
in my presentational component I compare if objects are equal
constructor(props) {
super(props);
this.state = {
name: "",
address: ""
};
}
componentWillReceiveProps(nextProps) {
_.isEqual(this.props.user, nextProps.user) ? (
this.setState({
name: this.props.user.name,
address: this.props.user.address
})
) : (
this.setState({
name: nextProps.user.name,
address: nextProps.user.address,
})
)
}
When you implement a Route like /users/:id, and if you change the id to something else, the entire component is not re-mounted and hence the componentDidMount is not called, rather only the props change and hence you need to implement componentWillReceiveProps function also
componentDidMount() {
this.props.getUserDetails(this.props.match.params.id);
}
componentWillReceiveProps(nextProps) {
if(this.props.match.params.id !== nextProps.match.params.id) {
this.props.getUserDetails(nextProps.match.params.id);
}
}

Resources